简体   繁体   中英

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. 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...

Iunno. Help is appreciated :)

The problem is that you have not allocated the setElement you are trying to assign to. In the main part of the code you are creating a Set , which is just a pointer to a 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. I assume your main.c is something like

#include "set.h"

Set a;    

int main()
{
    setInit(&a);
}

If so, your a, which is a pointer by itself, should point to somewhere.

If your framework wants malloc() ed data, you should do

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. In addition to this, you need to do the same for the setElement struct's element member. A char* is merely a pointer to a char or char array and will not implicitly allocate anything.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM