【发布时间】:2012-02-25 00:18:54
【问题描述】:
编写一个程序,在该程序中,我需要将结构链表中的字符串拆分为多个片段并重新组合它们。然后我将新的字符串重新插入到链接列表中。
我用来构建节点的结构如下所示:
typedef struct CANDIDATENODE
{
char sentence[TARGET_LEN+1];
int rank;
int score;
int goodFlag;
struct CANDIDATENODE *next;
} Candidate;
(TARGET_LEN是最大字符串长度。不包括空终止符,这就是+1的原因)
我没有遇到段错误或总线错误,但是在复制第三个字符后,下一次通过我的字符串数组填充了不属于的字符。 在程序的前面,我用随机字符填充链表中的 20 个节点。正是从这个节点列表中,我传递了候选指针
下面的 clearPointer 指向链接列表的末尾,我将在其中添加新句子。
这是问题方法的全部内容。
void breedSentences(Candidate *can1)
{
Candidate *can2 = can1->next;
char childOne[TARGET_LEN+1];
char childTwo[TARGET_LEN+1];
memset(childOne, '\0', sizeof(TARGET_LEN+1));
memset(childTwo, '\0', sizeof(TARGET_LEN+1));
printf("parent1:%s;\n", can1->sentence);
printf("parent2:%s;\n", can2->sentence);
int pivot1 = random() %TARGET_LEN-1;
int pivot2 = random() %TARGET_LEN-1;
printf("pivot1= %d\n", pivot1);
printf("pivot2= %d\n", pivot2);
int i;
for (i =0; i<TARGET_LEN-1; i++)
{
if (i<pivot1)
{
childOne[i]= can1->sentence[i];
}
else
{
childOne[i]= can2->sentence[i];
}
if (i<pivot2)
{
childTwo[i]= can1->sentence[i];
}
else
{
childTwo[i]= can2->sentence[i];
}
childOne[TARGET_LEN]= '\0';
childTwo[TARGET_LEN]= '\0';
printf("First:%c\n", can1->sentence[i]);
printf("Second:%c\n", can2->sentence[i]);
printf("1:%s\n", childOne);
printf("2:%s\n", childTwo);
}
printf("%s\n", childOne);
printf("%s\n", childTwo);
strcpy(clearPointer->sentence, childOne);
clearPointer = clearPointer->next;
strcpy(clearPointer->sentence, childTwo);
clearPointer = clearPointer->next->next;
}
【问题讨论】:
-
sizeof(TARGET_LEN+1) = sizeof(int)。 (Imp def,在你的系统上可能是 4)这不是你想要的。并不是说它真的需要它,因为无论如何你都是空终止它。
-
感谢真正导致我问题的人!
标签: c string struct linked-list