jam jam - 4 days ago 7
C Question

How to assign a void** array (return value of a function) to a variable?

Needed: A function which returns two different values (int,str)

So foo calculates smth. and stores the addresses of the two values
in the return array.

Now I want to read the values back into variables of these types.

void** foo(){
void** bar = malloc(2 * sizeof(void*));
...
return bar;
}


int main(int argc, char* argv[]){
void** result = foo();
int* val1 = (int*)result[0];
char* val2 = (char*)result[1];
}


This snippet is not compiling.

I have to excuse me:



the problem was not the code but that I declared it in a case branch
without any compution instructions.

int main(int argc, char* argv[]){
switch(xyz){
case a:
void** result = foo();
int* val1 = (int*)result[0];
char* val2 = (char*)result[1];
break;
}
}


Which seems not to make sense in a case.

Thanks though.

Answer

If you come up with the need to use a void**, it is a strong indication of poor program design. Just forget about this idea. void pointers in general is something you should avoid.

What you actually want to do seems to be something like this:

typedef struct
{
  int i;
  char c;
} something_t;

something_t* foo (void)
{
  something_t* result = malloc (sizeof(*result));
  ...
  return result;
}

int main(int argc, char* argv[]){
  something_t* result = foo();
  int* val1 = &result->i;
  char* val2 = &result->c;
}

If the struct members need to be pointers, simply change the struct.

Comments