C 中链表内的结构

发布于 2024-12-02 05:27:49 字数 528 浏览 0 评论 0原文

我正在学习如何在 C 中实现链表。我了解普通链表的基础知识,如何添加值,如何打印它们等。但我一直想知道 - 是否可以添加其他结构作为值链接列表?我的意思是:

typedef struct personal_info {
  char *name;
  char *surname;
  int phone_number;
} Info;

typedef struct llist {
  Info *info;
  struct llist *next;
} List;

当我这样做时,如何访问 Info 结构的值?

List *l;
l = malloc(sizeof(List));

l->info->name = 'name';
l->info->surname = 'surname';
l->info->phone_number = 1234567890;

代码崩溃了,所以我肯定做错了什么。您能给我一些如何实现这一目标的建议吗?

I'm learning how to implement linked lists in C. I understand the basics of normal linked lists, how to add values, how to print them etc. but I've been wondering - is it possible to add other structure as a value in linked list? What I mean is:

typedef struct personal_info {
  char *name;
  char *surname;
  int phone_number;
} Info;

typedef struct llist {
  Info *info;
  struct llist *next;
} List;

And when I do this, how do I access the values of the Info structure?

List *l;
l = malloc(sizeof(List));

l->info->name = 'name';
l->info->surname = 'surname';
l->info->phone_number = 1234567890;

The code crashes, so I'm definitely doing something wrong. Could you give me some tips how to achieve that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

勿忘初心 2024-12-09 05:27:49

您还需要为信息结构分配内存:

l = malloc(sizeof(List));
l->info = malloc(sizeof(Info));

l->info->name = "name";
l->info->surname = "surname";
l->info->phone_number = 1234567890;

You also need to allocate memory for the info struct:

l = malloc(sizeof(List));
l->info = malloc(sizeof(Info));

l->info->name = "name";
l->info->surname = "surname";
l->info->phone_number = 1234567890;
套路撩心 2024-12-09 05:27:49
List *l;
l = malloc(sizeof(List));
l->info = malloc(sizeof(Info));

您还必须为结构分配内存。

还请记住,如果您要实现从列表中删除节点的任何函数,则需要在释放节点之前释放该结构。

List *l;
l = malloc(sizeof(List));
l->info = malloc(sizeof(Info));

You have to malloc memory for the struct as well

Also remember that if you're implementing any functions that remove nodes from the list, you need to free that struct before you free the node.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文