gpt4 book ai didi

c - 使用循环将 Char 值添加到链接列表 [C]

转载 作者:行者123 更新时间:2023-11-30 17:38:27 25 4
gpt4 key购买 nike

我有一个链接列表,我目前正在尝试向其中添加值。但我的指针设置不正确,或者内存分配出了问题。

我想将标记添加到列表中,但每次出现新循环时数据都会重叠。例如:

第一次:

复制>一个一个

第二次:

repl> 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();
}
}

最佳答案

我在您的代码中发现以下问题:

  1. print_list ,您可能想要更改 printf(" %s\n",ptr->val);printf(" %c\n",ptr->val);如果您想将节点处的值打印为字符。
  2. 我不知道你为什么要增加pos在使用它之前。您可能打算在 create_list(storage[pos]); 行之后增加它.
  3. create_list 的参数类型是 int 。您正在传递 char *到它。也许你想通过storage[pos][0] .
  4. 您可能还指 tok = strtok(tok, " "); 。否则,while循环对你没有任何好处。

在我对计算机中的代码进行这些更改后,程序的行为就像您所期望的那样。

关于c - 使用循环将 Char 值添加到链接列表 [C],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22124297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com