2016-05-27 29 views
2

我使用此代碼插入數組data的值,但是當我嘗試插入值8 1 2 3 4 5 6 7 8(第一個數字8是數組的大小)時,輸出是00000000而不是輸入值1 2 3 4 5 6 7 8。任何想法如何讓程序工作?使用malloc插入數組的值

#include<stdio.h> 
#include<stdlib.h> 

int main() 
{ 
    int n,i,*data; 

    scanf("%d", &n); 

    data=(int *)malloc(sizeof(int)*n);//data[size] 

    for(i=0;i<n;i++) 
    { 
    scanf("%d", &data[i]); 
    } 

    for(i=0;i<=n;i++) 
    printf("%d",data[n]); 
    printf("\n"); 

    return 0; 
} 
+1

你有一個錯字'的printf( 「%d」,數據[N]);' - >'的printf( 「%d」,數據[I]);' – LPs

+1

我建議你自己幫忙,並學習如何使用調試器。它會幫助你快速找到這樣的微不足道的錯誤。 – user694733

+0

也'我<=n' -->'我 Lundin

回答

2

你需要改變這一部分:

for(i=0;i<=n;i++) 
    printf("%d",data[n]); 
    printf("\n"); 
    return 0; 
} 

到:

for(i = 0; i < n; i++) 
    printf("%d",data[i]); 
    printf("\n"); 
    return 0; 
} 

你做什麼現在迭代,但沒有使用可變i爲指標。相反,您不斷嘗試僅打印data[n]。這是一種訪問索引越界的,陣列的索引從0開始併到達n-1,其中n是陣列的尺寸。這會導致程序的[tag:undefined-behavior]。

所以你for循環將不得不爲:

for(i = 0; i < n; i++) 

或:

for(i = 0; i <= n-1; i++) 

此外,採取這種link on why you should not cast the result of malloc看看。此外,請確保您經常檢查malloc的結果,就像這樣:

data=malloc(sizeof(int)*n); 
if (data == NULL) 
    printf("Error in dynamically allocating memory.\n"); 
2
  1. 打印循環應當使用i爲指標,而不是n爲你
  2. 循環必須上去n-1,所以正確的條件必須是i<n。你的代碼訪問調用Undefined Behavior
  3. 的「數組」,你總是必須檢查函數的返回值。
  4. 附註:與you shouldn't cast malloc return

代碼

#include<stdio.h> 
#include<stdlib.h> 

int main() 
{ 
    size_t n,i; 
    int *data; 

    printf("Insert number of items: "); 
    scanf("%zu", &n); 

    data=malloc(sizeof(int)*n); 

    if (data != NULL) 
    { 
     for(i=0;i<n;i++) 
     { 
      printf("Insert value for item %zu: ", i+1); 
      scanf("%d", &data[i]); 
     } 

     printf("You inserted: "); 

     for(i=0;i<n;i++) 
      printf("%d ",data[i]); 
    } 
    else 
    { 
     fprintf(stderr, "Failed allocating memory\n"); 
    } 

    printf("\n"); 

    return 0; 
}