【发布时间】:2014-10-31 13:05:39
【问题描述】:
我正在尝试使用此示例在我的函数中实现链表: http://www.sanfoundry.com/c-program-create-linked-list-display-elements/
向下滚动到评论:
/** HERE. i don't want the "press 0 to exit",
* i want to take the new message from global var.
* then enter into a new node of the linked list.
**/
我的问题是我的代码执行错误,但不知道如何解决这个问题。 我想我需要一个循环退出策略,但我正在苦苦挣扎?
/**whenever i have a new message,
this global variable copies that message**/
char msg[30];
struct node{
char num[30];
struct node *ptr;
};
typedef struct node NODE; //call struct NODE
NODE *head, *first, *temp = 0; //initialize head, temp value to 0 and first
void function(
//if my message is available, then...
if(strlen(msg)!=0) {
while (choice){ //while true
head = (NODE *)malloc(sizeof(NODE));
//i copy the new string from the global variable declared above into
//the linked list....or that is what i am attempting to do
strcpy(head->num,msg);
printf("%s\n",s);
if (first != 0){
temp->ptr = head;
temp = head;
}
else{
first = temp = head;
}
i++;
/** HERE. i don't want the "press 0 to exit",
* i want to take the new message from global var.
* then enter into a new node of the linked list.
**/
choice=0;
}
temp->ptr = 0;
/* reset temp to the beginning */
temp = first;
while (temp != 0){
printf("%s\n", temp->num);
count++;
temp = temp -> ptr;
}
printf("No. of nodes in the list = %d\n", count);
}}
string1 上的输出:
string1
在新字符串 2 上输出:
string2
基本上在每个新字符串上,不断添加到链表并打印整个列表:
string1
string2
...
寻求任何帮助。
【问题讨论】:
-
很多代码丢失了。请提供MCVE。
-
我的实际代码太长了,所以我说msg(glob var.)每次都会复制新的字符串。
-
@user3035890 不要使用全局变量。重写没有全局变量的代码。
-
请提供main函数的代码
-
@VladfromMoscow 我有另一个生成字符串的函数,我将这些字符串复制到全局变量中
标签: c string loops while-loop linked-list