[英]Struct Pointers Segmentation Fault, How can I solve this?
我在 C 中有这些结构:
typedef struct Game{
char* name;
char* team_1;
char* team_2;
int score[2];
} *pGame;
typedef struct Team{
char *name;
int victories;
} *pTeam;
typedef struct node_game{
pGame game;
struct node_game *next;
} *link_game;
typedef struct node_team{
pTeam team;
struct link_team *next;
} *link_team;
typedef struct head{
link_game game_list;
link_team team_list;
} *pHead;
并将这些功能与 go 一起使用:
void initialize(pHead* heads,int m){
int i;
heads = (pHead*)malloc(m*sizeof(pHead));
for (i = 0; i < m; i++)
heads[i] = NULL;
}
//this function is to allocate dynamic memory for a string
char* str_dup(char* buffer){
char* str;
str = (char*) malloc(sizeof(char)*(strlen(buffer)+1));
strcpy(str,buffer);
return str;
}
void add_team(pHead* heads, char* name){
char* name_dup;
link_team new_team = (link_team) malloc(sizeof(struct node_team));
name_dup = str_dup(name);
new_team->team->name = name_dup; //this line gives me segmentation fault
}
int main(){
pHead* heads;
initialize(heads,M);
add_team(heads, "manchester");
return 0;
}
为什么 add_team 的最后一行给我分段错误? 我已经用 VSC 调试器查看了这个,它似乎应该 go 很好。 我的问题很可能是我没有在应该分配 memory 的时候,但我看不到在哪里。 (另外,function 会做更多的事情,但它已经给了我分段错误)。
在你这样做的时候:
new_team->team->name = name_dup;
您为 new_team 分配了new_team
,但没有为new_team->team
分配。 这意味着new_team->team->name
取消引用调用未定义行为的未初始化指针。
您需要先为其分配空间:
link_team new_team = malloc(sizeof(struct node_team));
new_team->team = malloc(sizeof(struct Team));
或者您可以将team
从struct Team *
更改为struct Team
并直接访问它。 您可能想对struct node_game
中的game
做同样的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.