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:
- i allocate dynamically space
struct test. - i allocate dynamically space
struct foo. - i assign value 5 member
aoffoo_ptr. - i assign address of allocated object of
struct foomembervaloftest_ptr. - i print member
astruct double pointervalpoints 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
Post a Comment