0

If I have the following struct:

struct myStruct {
    int value;
    struct myStruct *next;
};

and have an instance delcared as

struct myStruct *the_struct = (void *) malloc(sizeof(struct myStruct))

How do I access the "value" of *next?


I have tried doing

the_struct->next.value

and

*(the_struct->next)->value

but I receive error "dereferencing pointer to incomplete type."

jww
  • 97,681
  • 90
  • 411
  • 885
user2121620
  • 678
  • 12
  • 28
  • 2
    [In C you should not cast the result of `malloc`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Some programmer dude Oct 05 '14 at 19:50
  • Possible duplicate of [Confused about accessing struct members via a pointer](http://stackoverflow.com/questions/405537/confused-about-accessing-struct-members-via-a-pointer) – jww Oct 05 '14 at 19:56
  • the second one `(*the_struct->next).value` is valid. – Jason Hu Oct 06 '14 at 14:53

1 Answers1

1

You should use

 the_struct->next->value

but before that, you should be sure that the_struct->next is valid.

BTW, malloc(3) does fail, and it gives an uninitialized memory zone on success. So read also perror(3) and exit(3), then code:

struct myStruct *the_struct = malloc(sizeof(struct myStruct));
if (!the_struct) 
  { perror("malloc myStruct"); exit(EXIT_FAILURE); };
the_struct->value = -1;
the_struct->next = NULL;

(Alternatively, zero every byte of a successful result of malloc with memset(3), or use calloc instead of  malloc).

Later on, you might likewise get and initialize a struct myStruct* next_struct and finally assign the_struct->next = next_struct; and after that you could e.g. assign the_struct->next->value = 32; (or, in that particular case, the equivalent next_struct->value = 32;)

Please compile with all warnings and debug info (gcc -Wall -g) and learn how to use the debugger (gdb). On Linux, use also valgrind.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547