我正在尝试通过将指针传递到列表的开头来在函数内部创建链接列表。在函数内部,一切正常。但是,当我回到时main()
,指针突然变为NULL。因此,如果我再次调用该函数,则它的行为就像是我第一次添加节点一样。
我的代码有什么问题?
struct course
{
int c_ID;
char *c_name;
struct course *c_next;
};
void new_course(struct course *c_head, struct course *c_tail); // adds a node
int main ( )
{
// variable declarations
int choice;
char y_n;
// create linked lists
struct course *c_head = NULL;
struct course *c_tail = NULL;
// print out menu, obtain choice, call appropriate function; loop if desired
do
{
printf("\t\t\t***MENU***\n"
" 1. Add a new course\n\n"
................................
"Enter the number of the menu option you wish to choose: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
new_course(c_head, c_tail);
if (c_tail == NULL)
{
printf("We're screwed.\n"); // this excecutes every time
}
break;
.....................
}
printf("Would you like to return to the main menu? Enter y for yes, n for no: ");
scanf(" %c", &y_n);
} while (y_n != 'n' && y_n != 'N');
// free courses
struct course *c_temp = NULL;
c_temp = c_head;
while (c_temp != NULL)
{
c_head = c_head->c_next;
c_temp->c_ID = 0; // reinitialize the student ID
c_temp->c_name[0] = '\0'; // reinitialize the student name string
free(c_temp->c_name); // return the string memory to the system
free(c_temp); // return the node memory to the system
c_temp = c_head; // set temp to next item in the list
}
return 0;
}
void new_course(struct course *c_head, struct course *c_tail)
{
// declare variables
int ID;
char name[50];
// obtain user input
printf("Enter the course ID number and the course name, separated by a space: ");
scanf("%d%s", &ID, name);
if(c_head == NULL) // no courses yet
{
c_head = (struct course *) malloc(sizeof(struct course)); // allocate memory for c_head
c_head->c_next = NULL;
c_tail = c_head; // update c_tail
}
else // the list already has nodes
{
c_tail->c_next = (struct course *) malloc(sizeof(struct course)); // allocate memory for new node
c_tail = c_tail->c_next; // update c_tail
c_tail->c_next = NULL;
}
c_tail->c_ID = ID; // assign ID to c_ID component of new node
c_tail->c_name = (char *) malloc(sizeof(char) * strlen(name) + 1); // allocate memory for c_name component of new node
strcpy(c_tail->c_name, name); // assign name to c_name component of new node
printf("%d = %d, %s = %s\n", c_head->c_ID, ID, c_tail->c_name, name); // this always works, proving the list was created and the assignments worked
return;
}
您需要将指针传递给指针,以便可以更改c_head和c_tail的值。
像这样打电话
new_course(&c_head, &c_tail);
像这样使用
void new_course(struct course **c_head, struct course **c_tail)
{
if((*c_head) == NULL) // no courses yet
{
(*c_head) = (struct course *) malloc(sizeof(struct course));
... ETC。ETC。
}
我自己不会这样写,但这是您的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句