C 中链表内的结构
我正在学习如何在 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技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还需要为信息结构分配内存:
You also need to allocate memory for the info struct:
您还必须为结构分配内存。
还请记住,如果您要实现从列表中删除节点的任何函数,则需要在释放节点之前释放该结构。
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.