【发布时间】:2013-11-28 20:09:41
【问题描述】:
几周前我刚刚开始使用 C 进行编程,但我的程序出现了分段错误。
我相信是因为这些台词:
for (int i =0; i < HOW_MANY; i++)
{
people = people -> next;
if (people -> next == NULL) return people;
} //for
}//else
这是我的 C 程序,带有基于我的 psedocode 的 cmets
struct person *insert_end (struct person *people, char *name, int age) {
//create a new space for the new person
struct person *pointer = malloc(sizeof(struct person));
// check it succeeded
if(pointer == NULL)
{
printf("The program could not allocate memory ");
exit(-1);
}
// set the data for the new person
strcpy(pointer -> name, name);
pointer -> age = age;
pointer -> next = people;
// if the current list is empty
if (people == NULL)
{
// set the new person's "next" link to point to the current list"
pointer -> next = people;
// return a pointer to the new person
return pointer;
}
else
{
// we need a loop to find the last item in the list
// (the one which as a "next" link of NULL)
for (int i =0; i < HOW_MANY; i++)
{
// set the "next link of this item to point
// to the new person, so that the person
// becomes the last item in the list
// (the next person should have a "next" link of NULL)
people = people -> next;
if (people -> next == NULL)
return people;
} //for
}//else
// return the start of the list
return pointer;
}
另外,如果您需要我的完整 C 代码,请告诉我,因为这只是一种方法
谢谢,
莎拉 :)
【问题讨论】:
-
可能更适合CodeReview
-
你说
if (person == 0)和(*lastItem.next) = people;但没有变量叫做 person ad lastitem。而且还有其他类似的问题,所以很难弄清楚你在哪一部分遇到了麻烦。 -
如果你试图在列表的开头或结尾插入新的人,你的伪代码并不清楚这一事实,这很复杂。首先,您将新人放在列表的开头,然后将其放在列表的开头,然后执行循环以查找列表的结尾 - 更不用说当列表为空时您仍然指向它。
标签: c list linked-list segmentation-fault