gpt4 book ai didi

c - 向链接列表中插入元素

转载 作者:行者123 更新时间:2023-11-30 15:51:21 26 4
gpt4 key购买 nike

我正在参加 C 考试,在尝试将元素插入链接列表时,我遇到了运行时问题。我唯一的目的是将 4 个元素添加到列表中,然后打印列表。但是,它给出了一个错误。我已经查看了一些插入代码,我的代码看起来是正确的。看不到错误。任何帮助将不胜感激。

#include <stdio.h>
#include <stdlib.h>

struct ders{
char kod;
struct ders *next;

}*header;
typedef struct ders Ders;
void add(Ders*,Ders*);
void print(Ders*);

int main(void)
{

header = NULL;
Ders *node = NULL;
int i = 0;
char c;
while(i<4)
{
scanf("%c",&c);
node = (Ders*)malloc(sizeof(Ders));
node->kod = c;
node->next = NULL;
add(header,node );
i++;


}
print(header);

return 0;
}

void add(Ders *header, Ders *node)
{
if(header == NULL){
header = node;
header->next = NULL; }
else{
node->next = header;
header = node;

}
}

void print(Ders *header)
{
Ders *gecici = header;

while(gecici != NULL){
printf("%c\n",gecici->kod);
gecici = gecici->next;
}
}

最佳答案

正如 Nihirus 所说,“指针是按值传递的。因此,您可以更改它指向的内存,但无法更改实际的指针,即使其指向其他内容。”

您的修改导致错误*header is not member of struct因为 ->优先级高于 *

尝试使用 (*header)->next = NULL相反。

C 运算符优先级: http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm

关于c - 向链接列表中插入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15184901/

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