0

I've got a struct A and an array of pointers to instances of that struct
I'm trying to access a member directly from the array but I don't know what's the right syntax to do it :

struct A  
{  
  int a;  
  void** b;  
}

A* p = (A*) malloc(sizeof(A));  
p->b = (A**) malloc(sizeof(A*) * 3);

//
// something is done
//

int c;

A* test = p->b[0];
c = test->a;

Basically what I'm asking is how do I get rid of the intermediate A* test so I can assign the value of c in one line ?

4
  • 1
    Why void** and not struct A **? Commented Apr 7, 2016 at 15:32
  • That's irrelevent. I just need a void for what I'm doing but not showing here. The problem lies in the two last lines Commented Apr 7, 2016 at 15:34
  • p->b = (A**) malloc(sizeof(A*) * 3); is ill-formed, the compiler should complain Commented Apr 8, 2016 at 8:03
  • Are you sure you aren't using a C++ compiler? Commented Apr 8, 2016 at 13:20

2 Answers 2

2

Just do

int c = ((struct A*) (p->b[0]))->a;

Defining

struct A  
{  
  int a;  
  struct A ** b;  
}

this would do

int c = p->b[0]->a;
Sign up to request clarification or add additional context in comments.

2 Comments

That works, you rock ! So that void was kinda relevent after all ?
@user3548298: That's why I asked. ;-)
-1

You can do :

c = ((A*) (p->b[0]))->a;

1 Comment

You cannot, as A is not a type in C.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.