Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to using a triple pointer

Tags:

c

I have a pointer to a structure in my code. I want to return an array of such pointers in an API. Something like

Status GetData(MyStructure*** data, int*lengthOfArray)
  {
     *data = malloc(sizeof(MyStructure*)* arbitaryNumber));
     for(i=0....)
     {
       (*data)[i] = pointerToMyStructure;
     }
  }   

Is there an alternative to this? My API has to have a return type Status. So the only way forward I see at the moment is to turn into a 3 star programmer

like image 688
bobby Avatar asked May 01 '14 19:05

bobby


1 Answers

Since you are returning the length of the array as well, and because the array of struct pointers and the length are related, you could build a special struct to get both items from your API together, like this:

typedef struct {
    MyStructure **data;
    int length;
} GetDataArg_t;

Now you can change your API like this:

Status GetData(GetDataArg_t *args) {
    args->length = arbitaryNumbdr;
    args->data = malloc(sizeof(MyStructure*)* arbitaryNumbdr));
    for(i=0....) {
        args->data[i] = pointerToMytructure;
    }
}

The call of your API would look like this:

GetDataArg_t args;
if (GetData(&args) == STATUS_SUCCESS) {
    ...
}
like image 161
Sergey Kalinichenko Avatar answered Oct 16 '22 22:10

Sergey Kalinichenko