[英]Pointer to pointer in struct
有人可以幫助解釋為什么我的代碼的這一部分不起作用嗎?
typedef struct {
char *something;
} random;
random *rd;
rd->something = calloc(40, sizeof(char)); // This is the line which crashes
strncpy(rd->something, aChar, 40);
如果我這樣編寫程序,它將起作用:
random rd;
rd.something = calloc(40, sizeof(char));
strncpy(rd.something, aChar, 40);
但是我認為在處理內存時這是錯誤的,這就是為什么我需要第一種情況的幫助。
rd指向的結構沒有分配內存。
嘗試:
typedef struct {
char *something;
} random;
random *rd = malloc (sizeof(random));
rd->something = calloc(40, sizeof(char)); // This is the line which crashes
strncpy(rd->something, aChar, 40);
這是因為您定義的指針
random *rd;
未正確初始化,因此會出現分段錯誤。 第二個版本有效,因為您實際上分配了rd
。 為了使第一個版本也能正常工作,請使用以下命令為*rd
分配內存
random *rd = (random*)malloc(sizeof(random));
情況1:
random *rd;
// Create *pointer* to struct of type random . Doesn't point to anything.
rd->something = calloc(40, sizeof(char));
// Use it by trying to acquire something which doesnt exist and it crashes
情況2:
random rd;
// Create a random struct
rd.something = calloc(40, sizeof(char));
// Use it . Works good
==========================
對於案例1,您需要首先分配一個struct,使其指針指向它,然后使用->
運算符修改值
它將起作用,但是首先將內存分配給rd。 rd =(random *)calloc(1,sizeof(random));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.