我對 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;
}
我真的不明白。對不起,如果這是一個愚蠢的問題。
謝謝!
uj5u.com熱心網友回復:
usersisLInt和LIntis 的型別是type的別名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;
.....
.....
附加:遵循良好的編程習慣,確保檢查scanf()和等函式的回傳值malloc()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/379850.html
