C语言嵌套结构体初始化导致段错误的解决方案

在初始化结构体时,需要先为每个指针成员分配内存空间,然后再进行赋值操作。在你的代码中,没有为head->friendlist分配内存空间,所以在执行head->friendlist->next = NULL时会发生段错误。

//客户端好友结构体
typedef struct client_friend
{
    char client_name[50]; //客户端名称
    char client_IP[50]; //客户端IP
    int connfd; //客户端对应的已连接套接字
    struct client_friend *next;
}client_friend,*pclient_friend;

//客户端结构体
typedef struct client_info
{
    char client_name[50]; //客户端名称
    char client_IP[50]; //客户端IP
    struct client_friend *friendlist; //客户端好友链表
    int connfd; //客户端对应的已连接套接字
    struct client_info *next;
}client_info,*pclient_info;

pclient_info head=malloc(sizeof(client_info)); //申请客户端空间
head->friendlist->next = NULL; // 这里会导致段错误

你可以通过以下方式修改代码来避免段错误:

pclient_info head = malloc(sizeof(client_info)); // 申请客户端空间
head->friendlist = malloc(sizeof(client_friend)); // 为friendlist指针成员分配内存空间
head->friendlist->next = NULL;

这样,你就为head->friendlist分配了内存空间,并且将其next成员初始化为NULL

总结:

在初始化嵌套结构体时,一定要注意为每个指针成员分配内存空间,否则会导致段错误。

C语言嵌套结构体初始化导致段错误的解决方案

原文地址: https://www.cveoy.top/t/topic/foyt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录