[英]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.