[初學者問題] C pointer to struct
此程式是製作一個linked list (First in last out)但是在 add_to_list 這個 Function 內有點問題
每次 add_to_list 這個 Function 修改 list->value & list->next 的時候
只要一離開 add_to_list, 修改就會無效了, 變回預設值
所以我想請教一下有關 pointer's scope & 解決的辦法
謝謝
程序代码:/* testing a list */
#include <stdio.h>
#include <stdlib.h>
struct data
{
int value;
struct data* next;
};
int menu();
void call_related_function (int choice, struct data* list);
void add_to_list (struct data* list);
void remove_from_list (struct data* list);
void print_list (struct data* list);
/*
name:main
para: none
return: none
work: 1) print a menu (F)
3) call related function (F)
*/
int main()
{
int choice=0;
struct data* list = malloc(sizeof(struct data));
if (list==NULL)
{
printf("ERROR!!! Not enough memory.\n");
abort;
}
/* initializing list */
list->value=-1;
list->next=NULL;
/* Work */
printf( "This is a FILO list demonsration.\n");
do
{
choice=menu();
call_related_function (choice, list);
} while (choice!=4);
return 0;
}
/*
name: menu (main step 1)
para: none
return: int choice
work: 1) print a) add a value to list
b) remove a value from the list
c) print the list
2) get user's choice
3) return user's choice
*/
int menu()
{
printf( "1) Add a value to list.\n"
"2) Remove a value from list.\n"
"3) print the list.\n"
"4) Exit.\n"
"Please enter your choice: "
);
int choice = 0;
scanf("%d", &choice);
return choice;
}
void call_related_function (int choice, struct data* list)
{
switch (choice)
{
case 1:
add_to_list(list);
break;
case 2:
remove_from_list(list);
break;
case 3:
print_list(list);
break;
case 4:
break;
default:
printf("ERROR!!!! Wrong Input");
break;
}
}
/*
name: add_to_list
para: struct data* list
return: none
work: 1) ask for a value from user
2) Create a tmp pointer to list
3) allocate space for tmp pointer
4) set tmp pointer
5) set list pointer to tmp pointer
*/
void add_to_list (struct data* list)
{
printf("Value: ");
int value;
scanf("%d", &value);
/* For the first value */
if(list->value == -1)
list->value = value;
/* For the other value */
else
{
struct data* tmp = malloc(sizeof(struct data));
if(tmp==NULL)
{
printf("ERROR!!! Not enough memory.\n");
abort;
}
/* Add to list */
tmp->value = value;
tmp->next = list;
list = tmp;
}
}
/*
name: remove_from_list
para: struct data* list
return: none
work: 1) create a tmp pointer
2) set it pointing to the list
3) set list to tmp->next
4) free tmp
*/
void remove_from_list (struct data* list)
{
if(list->next!=NULL)
{
struct data* tmp = list;
list = tmp->next;
free(tmp);
}
}
/*
name: print_list
para: struct data* list
return: none
work: 1) create a tmp pointer pointer to list
2) print -> if i >0 (L)
2) print tmp->vale
*/
void print_list (struct data* list)
{
struct data* tmp = list;
int i=0;
printf("The list: ");
do
{
if(i>0)
printf(" -> ");
printf("%d", tmp->value);
i++;
}while(tmp->next!=NULL);
printf("\n");
}








