有人可以向我解释为什么ints从用户那里获取的内容scanf()存储在8h分开的地址中,即使int我的64位机器的大小是4字节?它与内存中的对齐?
#include <stdio.h>
void main() {
int *a;
int i, n;
printf(" Input the number of elements to store in the array : ");
scanf("%d",&n);
printf(" Input %d number of elements in the array : \n",n);
printf("size of on int is %d\n", sizeof(i));
for(i=0;i<n;i++) {
printf(" element - %d : ",i+1);
printf("address of a is %p\n", &a+i);
scanf("%d",a+i);
}
return 0;
}
Input the number of elements to store in the array : 3
Input 3 number of elements in the array :
size of on int is 4
element - 1 : address of a is 0x7ffda5cf8750
6
element - 2 : address of a is 0x7ffda5cf8758
5
element - 3 : address of a is 0x7ffda5cf8760
2
Run Code Online (Sandbox Code Playgroud)
小智 5
#include <stdio.h>
void main() {
int *a;
int i, n;
Run Code Online (Sandbox Code Playgroud)
您是否遗漏了以下代码?如果没有,a现在是一个具有不确定值的未初始化指针.
printf("address of a is %p\n", &a+i);
Run Code Online (Sandbox Code Playgroud)
在这里,您可以获取使用运算符的地址a&.结果是指向a IOW指针的指针.64位系统上指针的大小是8,所以这应该回答你的问题.
scanf("%d",a+i);
Run Code Online (Sandbox Code Playgroud)
在这里你写一些"随机"的内存位置.这是未定义的行为
供您参考,您似乎想要做的固定程序:
#include <stdio.h>
#include <stdlib.h> // <- needed for malloc()/free()
// use a standard prototype, void main() is not standard:
int main(void) {
int *a;
int i, n;
printf(" Input the number of elements to store in the array : ");
if (scanf("%d",&n) != 1)
{
// check for errors!
return 1;
}
// allocate memory:
a = malloc(n * sizeof(int));
for(i=0;i<n;i++) {
printf(" element - %d : ",i+1);
if (scanf("%d", a+i) != 1)
{
// again, check for errors!
return 1;
}
}
// [...]
// when done, free memory:
free(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
学习如何做输入更有力,阅读文档上scanf(),fgets(),strtol()...我准备一个小文件,但也有很多其他的资源可在网上,如本FAQ上SO.