有人可以向我解釋爲什麼從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)顯示指針。 –