我遇到了這個for循環的麻煩,我不明白爲什麼它崩潰。我試圖以「名字姓氏」格式讀取20個名字的輸入列表,並將它們存儲爲「姓氏,名字」中的字符串。不應將重複項存儲到數組指針中。不明白爲什麼C程序崩潰,字符串指針數組
當我註釋掉malloc和比較循環時,顯然有一些地址保持不變的問題,所以* ary返回與* walker相同的值。 filePtr的工作原理和strcpy和strcat函數沒有問題。此外,刪除第一個printf也會導致程序崩潰,即使刪除它似乎也不應該有除輸出外的任何實際效果。
FILE *filePtr = fopen ("input.txt","r");
int size = 20;
char **ary;
char **walker;
char **end;
int strsize = 0;
char firstname[30] = {0};
char lastname[30] = {0};
char *fullname;
ary = calloc (size, sizeof(char *));
printf("%d\n",sizeof(pAry));
for (walker = ary ; *walker < (*end = *ary + size) ; walker++)
{
fscanf(filePtr," %s",firstname);
fscanf(filePtr," %[^\n]",lastname);
strsize = strlen(firstname) + strlen(lastname) + 3;
fullname = malloc (strsize * sizeof(char));
strcpy(fullname,lastname);
strcat(fullname,", ");
strcat(fullname,firstname);
for (compare = 0 ; compare < walker ; compare++)
{
if(strcmp(fullname,*(ary + compare)) != 0)
{
diff = 0;
}
}
if (diff)
{
strncpy(*walker,fullname,strsize);
printf("%s\n",*walker);
}
free(fullname);
}
究竟是布爾條件在這裏:'*沃克<(*結束= *元+大小)'? – Oleksiy
@OleksiyDobrodum它應該檢查walker字符串是否已經到達數組的末尾 – user2649387
這裏有一個提示:什麼是C中的相等運算符?什麼是賦值運算符? –