使用循环将C值添加到链接列表
我有一个链接列表,我正在尝试为其添加值。 但是我必须错误地设置我的指针,或者内存分配有问题。
我想将令牌添加到列表中,但每次有新的循环时数据都会重叠。 例如:
第一次:
repl> a a
第二次:
repl> b b
b
注意a是如何消失的,我想在添加新值时保留先前的值。
到目前为止,这是我的代码:
struct node { int val; struct node *next; }; struct node *head = NULL; struct node *cur = NULL; struct node* create_list (int value) { struct node *ptr = (struct node*) malloc(sizeof (struct node)); if (NULL == ptr) return NULL; ptr->val = value; ptr->next = NULL; ptr->next = head; head = ptr; return ptr; }; struct node* insertion (int value) { if (NULL == head) return (create_list(value)); struct node *ptr = (struct node*)malloc(sizeof(struct node)); ptr->val = value; ptr->next = NULL; ptr->next = head; head = ptr; return ptr; }; void print_list(void) { struct node *ptr = head; while(ptr != NULL) { printf(" %s\n",ptr->val); ptr = ptr->next; } return; } struct exp { int type; union { int num; char name; double decimal; char strq; } value; }; int main(int argc, char *argv[]) { while(1) { printf("repl>"); char *storage [30]; char* tok; char g; char buffer[20]; int pos = 0, i; fgets(buffer,sizeof(buffer),stdin); tok = strtok(buffer," "); while(tok) { pos++; storage[pos] = tok; create_list(storage[pos]); tok = strtok(NULL," "); } print_list(); } }
我在您的代码中看到以下问题:
- 在
print_list
,您可能想要更改printf(" %s\n",ptr->val);
toprintf(" %c\n",ptr->val);
如果要将节点上的值作为字符打印。 - 我不知道为什么你在使用它之前增加
pos
。 你可能想在行create_list(storage[pos]);
之后增加它create_list(storage[pos]);
。 -
create_list
的参数类型是int
。 你正在传递一个char *
。 也许你打算通过storage[pos][0]
。 - 你可能也意味着
tok = strtok(tok, " ");
。 否则,while
循环对你没有好处。
在我的计算机中对代码进行了这些更改后,程序的行为就像您预期的那样o。