我想在C中有一些動態增長的數組/數據結構。下面是我擁有的C代碼。但是在打印數組後,它會產生運行時錯誤,如下面的快照中所示。出了什麼問題?它正在Windows-7上使用MS-Visual C++ 2010(免費版)進行編譯。這個C代碼中使用realloc的錯誤是什麼?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a;
int i = 5;
if((a = (int *)malloc(i * sizeof(int))) == NULL) {
fprintf(stderr, "Error: failed malloc\n");
return 1;
}
for(i = 0; i < 5; i++)
a[i] = i;
printf("-- array after malloc\n");
for(i = 0; i < 5; i++)
printf(" a[%d] = %d\n", i, a[i]);
if((a = (int *)realloc(a, i * sizeof(int))) == NULL) {
fprintf(stderr, "Error: failed realloc\n");
return 1;
}
for(i = 0; i < 10; i++)
a[i] = i;
printf("\n-- array after realloc\n");
for(i = 0; i < 10; i++)
printf(" a[%d] = %d\n", i, a[i]);
free(a);
return 0;
}
'i'是4,而不是5 – orlp
@nightcracker:'i'是5,而不是4 :) –
喔woops :)(15個字符) – orlp