2013-10-10 157 views
0

我只是想malloc一個字符串數組,並從一個文件複製輸入到這個數組。這種行的組合導致段錯誤,我不知道爲什麼。爲什麼會導致段錯誤?

int count = 0; 
char **output = (char**)malloc(numLines*257); 
fgets(output[count], 257, input); 
+0

不要投malloc的:http://stackoverflow.com/questions/605845/do- i-cast-the-result-of-malloc – Barmar

回答

5

您已經爲指針數組分配了空間,但尚未初始化任何這些指針。

int count = 0; 
char **output = malloc(numLines*sizeof(char *)); 
int i; 
for (i = 0; i < numLines; i++) { 
    output[i] = malloc(257); 
} 
fgets(output[count], 257, input); 
+0

感謝您的幫助。 – slmyers

1

我覺得你真正想在這裏做的是分配內存numLines指針(串),然後爲每個字符串分配內存,使每一項都是能夠保持257char S:

int i, count = 0; 
char **output = malloc(sizeof(char*) * numLines); 
for (i = 0; i < numLines; ++i) 
    output[i] = malloc(257); 
... 
fgets(output[count], 257, input); 

只是不要忘了把它清理乾淨,一旦你不需要它了:

for (i = 0; i < numLines; ++i) 
    free(output[i]); 
free(output); 
output = NULL; 
1
int count = 0; 
char **output = (char**)malloc(numLines*257); 
fgets(output[count], 257, input); // here You are going wrong, with out allocating memory you are trying to read. 

,如果你想讀的字符串

char *output = malloc(MAX_LENGTH+1); //allocate memory 
    fgets(output[count], MAX_LENGTH+1, input); 

,如果你想讀的字符串數組

char **output = malloc(MAX_NUM_STRINGS * sizeof(char *)); //allocate Number of pointers 
for(count=0;count<MAX_NUM_STRINGS;count++) 
{ output[count]=malloc(SIZE_OF_EACH_STRING+1); //allocate memory for each pointer, 
    //You are accessing with out allocating memory 
    fgets(output[count], SIZE_OF_EACH_STRING+1, input); 
} 
相關問題