2017-06-14 29 views
-3

有人可以向我解釋爲什麼從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 
+1

'%d'需要一個'int'。 'sizeof'產生'size_t' - >未定義的行爲。 – Olaf

+1

'&a'取指針的地址,指針需要8個字節。您在代碼中還有其他問題需要擔心,比如寫入無效位置('a'沒有指向任何有效位置!) –

+1

'printf(「地址是%p \ n」,(void *)(a + i));'會通過sizeof(int)'(4)顯示指針。 –

回答

5
#include <stdio.h> 
void main() { 

    int *a; 
    int i, n; 

有以下省略你的任何代碼?如果不是,a現在是一個未初始化的指針,具有不確定的值。

printf("address of a is %p\n", &a+i); 

在這裏,你需要使用&運營商a地址。結果是指向a,IOW指向指針的指針。一個64位系統上的指針大小是8,所以這應該回答你的問題。

scanf("%d",a+i); 

在這裏你寫了一些「隨機」的內存位置。這是不確定的行爲


供您參考,爲你似乎什麼固定的程序想做的事:

#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; 
} 

學習如何做輸入更有力,對scanf()閱讀文檔,fgets()strtol() ...我準備了a little document,但網上有很多其他資源可用,例如this FAQ on SO

+0

另外,如果您使用的是Microsoft編譯器,請查看防止緩衝區溢出的更安全的scanf版本(例如s_scanf)。 – Neil

+3

@Neil no,'scanf_s'是完全不必要的,只是試圖鎖定供應商。對於轉換爲字符串,只需使用'scanf()'以適當的字段寬度。 –

+0

真的嗎?所以scanf(「%s」,charArray)中沒有可能的緩衝區溢出? – Neil

相關問題