-1

I want to access members of a struct from double pointer but I get the 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 is already malloced and populated*/
  printf ("Value of a is %d", ptr->(*val)->a);
}

I've also tried:

*ptr.(**foo).a
Community
  • 1
  • 1

2 Answers2

0

You want to do 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 to (*foo_ptr).a = 5;
    test_ptr->val = &foo_ptr;
    printf ("Value of a is %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 a is 5

In my example:

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

Note, in your example: struct foo is a type, so it doesn't make sense to ask for its address.

Also, you were missing a semicolon when you were done with the declaration of struct foo.

Oh, and make sure not to cast the return value of malloc().

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
-2

in ptr->val = &foo;, foo is a struct (you declared it in lines 5 to 7). Taking its address does not give a **, but only a *.

Also it seems multiple things have the same names; is a foo the name of a structure or an instance of it, or both?

Then, when you dereference it: ptr->(*val)->a does seem the wrong sequence. as ptr->val is the address of foo (that's what you assigned in the line above it), what would ptr->(*val) be??

I think ptr->val.a would give you your a. But still, the val is declared as a ** and consistently used as a *. It might work, but makes not much sense.

Aganju
  • 6,295
  • 1
  • 12
  • 23
  • 1
    `foo` and `struct foo` are unrelated (struct tags have a separate "namespace" to other names). But even if they were the same thing, you can't take the address of a type – M.M Aug 29 '16 at 01:23
  • That was my point. Surely, you can name all your things the same name and trust the compiler to keep it sorted out. But it is not helping maintainability and human understanding of the code. It would be better to give it different names, even if not required. – Aganju Aug 29 '16 at 02:03