有人可以向我解释为什么从scanf()
用户接收的ints
存储在相隔8h
的地址,即使大小我的64位机器上有4个字节的int
?这是与内存中的对齐?c程序 - 为什么整数存储间隔8小时,即使它们占用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
'%d'需要一个'int'。 'sizeof'产生'size_t' - >未定义的行为。 – Olaf
'&a'取指针的地址,指针需要8个字节。您在代码中还有其他问题需要担心,比如写入无效位置('a'没有指向任何有效位置!) –
'printf(“地址是%p \ n”,(void *)(a + i));'会通过sizeof(int)'(4)显示指针。 –