C: Accessing pointer to pointer to struct element from pointer to structure -


i want access members of struct double pointer error

"error: expected identifier before ‘(’ token"

:

struct test{   struct foo **val; };  struct foo{   int a; }  int main (){   struct test *ptr = (struct test *)malloc(sizeof(struct test));   ptr->val = &foo;   /*foo malloced , populated*/   printf ("value of %d", ptr->(*val)->a); } 

i've tried:

*ptr.(**foo).a 

you want this:

#include <stdio.h> #include <stdlib.h>  struct test {     struct foo **val; };  struct foo {     int a; };  int main(void) {     struct test* test_ptr = malloc(sizeof(struct test));     struct foo* foo_ptr = malloc(sizeof(struct foo));     foo_ptr->a = 5;    // equivalent (*foo_ptr).a = 5;     test_ptr->val = &foo_ptr;     printf ("value of %d\n", (*(test_ptr->val))->a);     free(test_ptr);     free(foo_ptr);     return 0; } 

output:

c02qt2ubfvh6-lm:~ gsamaras$ gcc -wall main.c  c02qt2ubfvh6-lm:~ gsamaras$ ./a.out value of 5 

in example:

  1. i allocate dynamically space struct test.
  2. i allocate dynamically space struct foo.
  3. i assign value 5 member a of foo_ptr.
  4. i assign address of allocated object of struct foo member val of test_ptr.
  5. i print member a struct double pointer val points to.

note, in example: struct foo type, doesn't make sense ask address.

also, missing semicolon when done declaration of struct foo.

oh, , make sure not cast return value of malloc().


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -