[英]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.