如何在C中使用结构?

如何在C中使用结构?,c,struct,C,Struct,这是C编程语言中链表的代码 #include <stdio.h> /* For printf */ #include <stdlib.h> /* For malloc */ typedef struct node { int data; struct node *next; /* Pointer to next element in list */ } LLIST; LLIST *list_add(LLIST **p, int i); voi

这是C编程语言中链表的代码

#include <stdio.h>    /* For printf */
#include <stdlib.h>   /* For malloc */

typedef struct node {
    int data;
    struct node *next; /* Pointer to next element in list */
} LLIST;

LLIST *list_add(LLIST **p, int i);
void list_remove(LLIST **p);
LLIST **list_search(LLIST **n, int i);
void list_print(LLIST *n);
#包括/*用于printf*/
#包括/*用于malloc*/
类型定义结构节点{
int数据;
结构节点*next;/*指向列表中下一个元素的指针*/
}利斯特;
LLIST*列表添加(LLIST**p,int i);
删除无效列表(列表**p);
LLIST**列表搜索(LLIST**n,int i);
作废清单打印(LLIST*n);

代码还没有完成,但我想这已经足够回答我的问题了。这里在结构节点的末尾使用了“LLIST”,它也用作函数
列表\u add
原型中的返回类型。发生了什么事?

LLIST只是已创建结构的另一个类型名。通常,以下格式将创建类型“NAME”,即“struct x”:


这是一个
typedef
。它实际上同时做两件事。首先,它定义了一个结构:

struct node {
    int data;
    struct node *next;
}
然后执行
typedef

typedef struct node LLIST;

这意味着
LLIST
是一种类型,就像
int
FILE
char
一样,是链表节点结构
struct node
的缩写。这是不必要的-您可以在所有这些位置将
LLIST
替换为
struct node
,但这会使它更易于阅读,并有助于向讨厌的最终用户隐藏实现。

C要求您使用“struct”前缀引用结构,因此引入typedef以减少冗长的提及是很常见的

也就是说,结构的声明有两部分,可以重写为:

struct node {
    int data;
    struct node *next; /* pointer to next element in list */
};

typedef struct node LLIST;

因此,
LLIST
只是
struct节点的另一个名称(感谢Chris Lutz)。

LLIST*
是指向
LLIST
结构定义的结构的指针

你应该这样做

LLIST* myList = malloc(sizeof(LLIST)*number_of_elements);
为该列表分配一些内存。添加和删除项需要使用realloc重新分配内存。我已经为列表(使用数组制作)编写了一些代码


我可能会在回家后立即发布代码,但目前情况并非如此。

typedef
会在程序中创建一个新的“类型”,因此这些函数的返回值和参数类型就是您的结构。它只是对类型使用
struct node
的简写

如果要创建新节点,可以这样做(使用类型):

同样,对于你的问题中的函数原型,你并不真的需要双指针;由于结构中的数据只是一个
int
,因此可以执行以下操作

LLIST *list_add(int data, int position);
然后,
list\u add
函数将处理分配,将
int
复制到结构中,并将其添加到链表中

将其置于某个位置非常简单,只需将其前面节点中的
next
指针更改为新分配节点的地址,将新节点中的
next
指针更改为指向下一个节点(该节点之前的节点最初指向的节点)

请记住(考虑到函数原型的其余部分),您必须跟踪指向您创建的每个节点的指针,以便将它们全部删除


我不确定我是否理解搜索功能将如何工作。这整件事可以实施得更好。创建节点时不必提供节点的位置(如果指定的节点数大于节点数会怎么样?)等等。

从技术上讲,应该为列表中的每个项目执行
malloc
,因为它严格来说不是一个列表,而是一个带有指向列表中下一个项目的指针(
*next
)的结构。因此,在创建每个列表项时,您将执行一个单独的malloc。
LLIST *node = malloc(sizeof(LLIST));
node->data = 4;
node->next = someOtherItem;
list_add(node, 1)
LLIST *list_add(int data, int position);