[英]Segmentation fault using multiple structs
我是 C 的新手。 我在使用指針和類似的東西時遇到了一些麻煩。
我編寫了這段代碼試圖理解為什么它會返回分段錯誤。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct lligada {
int userID;
struct lligada *prox;
} *LInt;
typedef struct {
int repo_id;
LInt users;
} Repo;
typedef struct nodo_repo {
Repo repo;
struct nodo_repo *left;
struct nodo_repo *right;
} *ABin_Repos;
void createList (int id_user, int id_repo) {
ABin_Repos temp = malloc(sizeof(struct nodo_repo));
temp->repo.repo_id = id_repo;
temp->repo.users->userID = id_user;
temp->left = NULL;
temp->right = NULL;
printf("%d", temp->repo.users->userID);
}
int main() {
int id_user, id_repo;
scanf("%d %d", &id_user, &id_repo);
createList(id_user, id_repo);
return 0;
}
我真的不明白。 對不起,如果這是一個愚蠢的問題。
謝謝!
users
的類型是LInt
,而LInt
是struct lligada *
類型的別名:
typedef struct lligada {
int userID;
struct lligada *prox;
} *LInt;
這意味着users
的類型是struct lligada *
。
在createList()
中,您在分配users
指針之前訪問它。 因此,您遇到了分段錯誤。
你應該做:
void createList (int id_user, int id_repo) {
ABin_Repos temp = malloc(sizeof(struct nodo_repo));
// Allocate memory to users
temp->repo.users = malloc (sizeof (struct lligada));
// check malloc return
if (temp->repo.users == NULL) {
// handle memory allocation failure
exit (EXIT_FAILURE);
}
temp->repo.repo_id = id_repo;
temp->repo.users->userID = id_user;
.....
.....
附加:遵循良好的編程習慣,確保檢查 function 的返回值,如scanf()
和malloc()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.