Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C链接列表问题_C - Fatal编程技术网

C链接列表问题

C链接列表问题,c,C,我不确定我试图用C语言创建的以下简单LinkedList实现有什么问题。我尝试使用printf语句调试代码,在最终的printf语句之前,一切似乎都匹配。非常感谢您的帮助 #include <stdio.h> #include <string.h> struct Cell { int info; struct Cell *next; }; void add(struct Cell *orig, int a) { struct Cell newC

我不确定我试图用C语言创建的以下简单LinkedList实现有什么问题。我尝试使用printf语句调试代码,在最终的printf语句之前,一切似乎都匹配。非常感谢您的帮助

#include <stdio.h>
#include <string.h>

struct Cell
{
    int info;
    struct Cell *next;
};

void add(struct Cell *orig, int a)
{
    struct Cell newCell;
    orig->next = &newCell;
    newCell.info = a;
    printf("New Cell: %d\n", newCell.info);
    printf("New Cell Address: %x\n", &newCell);
    printf("Test: %d\n", (&newCell)->info);
}

int main()
{
    struct Cell LinkedList;
    struct Cell *ip = &LinkedList;

    /* First Element */
    LinkedList.info = 10;

    add(ip, 15);

    printf("#1: %d\n", ip->info);
    printf("Adress: %x\n", ip->next);
    printf("#2: %d\n", (ip->next)->info); 

    return 0;
}
#包括
#包括
结构单元
{
国际信息;
结构单元*下一步;
};
空添加(结构单元*原始,整数a)
{
结构细胞-新细胞;
原始->下一步=&newCell;
newCell.info=a;
printf(“新单元格:%d\n”,newCell.info);
printf(“新单元地址:%x\n”,&newCell);
printf(“测试:%d\n”,(&newCell)->info);
}
int main()
{
结构单元链接列表;
结构单元*ip=&LinkedList;
/*第一要素*/
LinkedList.info=10;
增加(ip,15);
printf(“#1:%d\n”,ip->info);
printf(“地址:%x\n”,ip->next);
printf(“#2:%d\n”,(ip->next)->info);
返回0;
}

尝试此添加功能以解决此问题

void add(struct Cell *orig, int a)
{
   struct Cell *newCell=(struct Cell *)malloc(sizeof(struct Cell));
   orig->next = newCell;
   newCell->info = a;
   printf("New Cell: %d\n", newCell->info);
   printf("New Cell Address: %x\n", &newCell);
   //printf("Test: %d\n", newCell)->info);
}

对于链表的构建,您应该使用库
stdlib.h

中的
malloc()
函数将内存分配给每个节点。您的代码首先有编号问题,malloc在哪里?应该始终使用malloc为链接列表的每个节点分配足够的内存,以便编译器分配内存并为您返回指针。 此外,当插入第一个节点时,您需要一个指向指针操作的指针! 因为指向列表第一个nide的指针实际上是指向指针的指针,而指针本质上就是列表的地址。因此,您应该使用if语句插入第一个节点,并确保更改列表的地址 最重要的是
请认真练习指针,因为它们很难掌握,但值得掌握

提示:在
add
中应该有一个对
malloc
的调用。是的,我很确定在对
add()
的调用完成后,您的“newCell”节点超出了范围(即被清除)。您研究过动态内存(heap)吗?这里只使用堆栈对象。