簡體   English   中英

指針數組(指向結構)

[英]Array of pointers (to structs)

我正在嘗試做這樣的事情

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    
}

我需要一個指向idk大小的結構的指針數組

使用在函數外部聲明的“雙指針”是解決此問題的最佳方法嗎? 那么為結構分配空間呢?

您可以聲明為全局,然后在函數內部分配內存。

如果要為數組分配內存。

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.

}   

如果要為指針數組分配內存。

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));
   }
}  

不要忘記free()用malloc分配的內存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM