【问题标题】:Inserting an Element to a Linked List将元素插入链接列表
【发布时间】:2013-02-17 13:23:23
【问题描述】:

我正在参加 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;
}
}

【问题讨论】:

  • 您的 header 变量始终为 NULL,因为您从未为其分配任何其他内容。

标签: c linked-list insertion


【解决方案1】:

正如 nihirus 所说, “指针是按值传递的。因此你可以改变它指向的内存,但你不能改变实际的指针,即让它指向别的东西。”

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

尝试使用 (*header)-&gt;next = NULL 而是。

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

【讨论】:

  • 谢谢。我设法添加了一个元素。我想问最后一个问题只是为了澄清。如果我们这样做 void(int *a),它需要一个整数数组或整数的地址。换句话说,通过引用调用。为什么“void(Ders *a)”需要一个指针的副本?如果我想为指针创建 callbyref,我必须使用 ** 吗?这样做是否明智:void(char **a)?
猜你喜欢
  • 2018-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多