我有一个“名称”(字符串)字段的有序结构列表(CASE)。我想创建一个带有参数“name”(字符串)和“count”(整数)的新结构(ARTCOUNT)。
结构:
typedef struct
{
char* name;
char* art;
int rating;
}CASE;
typedef struct
{
char* name;
int count;
}ARTCOUNT;
我将遍历 CASE 数组,如果 CASE 中的“名称”与 ARTCOUNT 中的名称匹配,我会将计数加 1,否则我将使用新名称创建一个新的 ARTCOUNT 数组并继续遍历数组。
如果名称匹配,当我尝试添加计数时,我遇到的问题是一个奇怪的分段错误。
/*all is the array of CASE and pLast points to the last CASE in all*/
void countArt(CASE* all, CASE* pLast)
{
CASE* walker = all;
ARTCOUNT* artAll;
ARTCOUNT* artWalker = artAll;
ARTCOUNT* artLast;
if((artAll = (ARTCOUNT*)malloc(sizeof(ARTCOUNT)*(pLast-all+1))) == NULL)
{
printf("Fatal memory error!\n");
exit(1);
}
artWalker->name = (char*)malloc(sizeof(char)*(100));
strcpy(artWalker->name, walker->name);
artWalker->count = 1;
for(walker = all+1; walker <= pLast; walker++)
{
if (strcmp(walker->name, artWalker->name) == 0)
{
artWalker->count += 1;
}
else
{
artWalker++;
artWalker->name = (char*)malloc(sizeof(char)*(100));
strcpy(artWalker->name, walker->name);
artWalker->count = 1; //if I comment this out, no segmentation fault
}
}
artLast = artWalker;
return;
}
正如上面的代码中提到的,我设法缩小了可能是错误的范围artWalker->count-1;
。如果我注释掉这一行,错误就会消失。但是,如果我尝试在循环中打印say artWalker->name,我仍然会收到分段错误。我已经多次检查了我的内存分配,但我认为不是这样。
有小费吗?