简体   繁体   中英

Array of pointers (to structs)

I'm trying to do something like this

typedef struct _thingy_t
{
    int num;
} thingy_t;

void go(int idk)
{
    // normally I could just do
    thingy_t* ary[idk];
    // but I need the array to be global    
}

I need an array of pointers to structs of size idk

Is using a 'double pointer' declared outside of the function the best way to go about this? And what about malloc'ing space for the structs?

You can declare as global and then allocate memory inside function.

if you want to allocate memory for array.

void go(int);  

thingy_t *data=NULL; 
main()
{

   //read idk value.
   go(idk);

}
void go(int idk)
{
        data = malloc(idk * sizeof(thingy_t) );
       // when you allocate memory with the help of malloc , That will have scope even after finishing the function.

}   

if you want to allocate memory for array of pointers.

thingy_t **data=NULL;

int main()
{
    int i,idk=10;
    go(idk);

    for(i=0;i<10;i++)
       {
       data[i]->num=i;
       printf("%d ",data[i]->num );
       }

return 0;
}

void go(int idk)
{
   int i=0;
   data=malloc(idk *sizeof( thingy_t * ));
   for ( i = 0; i<idk ; i++) {
      data[i]=malloc(sizeof( thingy_t));
   }
}  

Don't forgot to free() the memory which is allocated with malloc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM