[英]Pointer to pointer in struct
Could someone help explaining why this part of my code isn't working? 有人可以帮助解释为什么我的代码的这一部分不起作用吗?
typedef struct {
char *something;
} random;
random *rd;
rd->something = calloc(40, sizeof(char)); // This is the line which crashes
strncpy(rd->something, aChar, 40);
The program works if I write it as such: 如果我这样编写程序,它将起作用:
random rd;
rd.something = calloc(40, sizeof(char));
strncpy(rd.something, aChar, 40);
But I think this is wrong when handling memory, that's why I want help with the first scenario. 但是我认为在处理内存时这是错误的,这就是为什么我需要第一种情况的帮助。
There's no memory allocated to the struct pointed by rd. rd指向的结构没有分配内存。
Try: 尝试:
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);
It is because your defined pointer 这是因为您定义的指针
random *rd;
is not properly initialized and therefore you get a segmentation fault. 未正确初始化,因此会出现分段错误。 The second version works, because you actually allocate rd
. 第二个版本有效,因为您实际上分配了rd
。 To make the first version work as well, allocate memory for *rd
with 为了使第一个版本也能正常工作,请使用以下命令为*rd
分配内存
random *rd = (random*)malloc(sizeof(random));
Case 1: 情况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
Case 2: 情况2:
random rd;
// Create a random struct
rd.something = calloc(40, sizeof(char));
// Use it . Works good
=========================== ==========================
For Case 1, you need to allocate a struct first , make the pointer point to it and then use the ->
operator to modify the values 对于案例1,您需要首先分配一个struct,使其指针指向它,然后使用->
运算符修改值
It will work, but first allocate memory to rd. 它将起作用,但是首先将内存分配给rd。 rd = (random *) calloc(1,sizeof(random)); rd =(random *)calloc(1,sizeof(random));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.