[英]Accessing members in a pointer to a pointer of a struct
Code is as follows: 代码如下:
/* set.h */
struct setElement{
char *element;
setElement *next;
};
typedef struct setElement *Set; //Set is now the equivalent of setElement*
Set a;
setInit(&a);
/* setInit function declaration @ setInit.c */
int setInit(Set *a){
(*a)->element = "asdf"; //results in a seg fault
}
Trying to malloc 'a' works, but if I try to access any member within the set 'a' doesn't work. 尝试malloc'a'有效,但是如果我尝试访问集合'a'中的任何成员都行不通。 I understand I'm passing a reference of the set from the main() function to setInit, so I believe the pointer contained within setInit is addressing the memory allocated by 'Set a' in the main() function, so a malloc wouldn't be required...
我知道我正在将对set的引用从main()函数传递给setInit,因此我相信setInit中包含的指针正在寻址main()函数中“ Set a”分配的内存,因此malloc不会不需要...
Iunno. no野 Help is appreciated :)
感谢您的帮助:)
The problem is that you have not allocated the setElement
you are trying to assign to. 问题是您尚未分配要分配给的
setElement
。 In the main part of the code you are creating a Set
, which is just a pointer to a setElement
. 在代码的主要部分中,您将创建一个
Set
,它只是一个指向setElement
的指针。 This pointer is never set to point to anything sensible. 此指针永远不会设置为指向任何明智的指针。 Ie you need something like
即您需要类似的东西
Set a = malloc(sizeof(setElement));
Alas, it is unclear where exactly your variables are defined. las,尚不清楚您的变量的确切定义位置。 I assume your
main.c
is something like 我认为你的
main.c
就像
#include "set.h"
Set a;
int main()
{
setInit(&a);
}
If so, your a, which is a pointer by itself, should point to somewhere. 如果是这样,您的a(本身就是一个指针)应该指向某个地方。
If your framework wants malloc()
ed data, you should do 如果您的框架需要
malloc()
ed数据,则应该这样做
int main()
{
a = malloc(sizeof(*a)); // *a is a struct setElement now, with 2 pointer-sized members.
setInit(&a); // Now seInit should be able to operate on the struct as wanted.
}
As @amaurea has mentioned, you'll need to make use of malloc() for your setElement structure. 正如@amaurea所提到的,您需要在setElement结构中使用malloc()。 In addition to this, you need to do the same for the setElement struct's
element
member. 除此之外,您还需要对setElement结构的
element
成员执行相同的操作。 A char*
is merely a pointer to a char or char array and will not implicitly allocate anything. char*
仅仅是指向char或char数组的指针,不会隐式分配任何内容。
int setInit(Set *a){
(*a)->element = "asdf"; //results in a seg fault
}
Could be re-written 可以改写
int setInit(Set *a){
(*a)->element = malloc(sizeof("asdf"));
strcpy((*a)->element,"asdf");
}
Which the above could be rewritten to take a second parameter of the actual element
contents. 以上内容可以重写为采用实际
element
内容的第二个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.