我遇到了这个 for 循环的问题,我不明白它为什么会崩溃。我正在尝试以“名字姓氏”格式读取 20 个名称的输入列表,并将它们作为字符串存储在“姓氏,名字”中。不应将重复项存储到数组指针中。
当我注释掉 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);
}