[英]Setting pointer in struct to an array in C
我正在調試一些代碼,只是想確保我在結構體中設置指向數組的指針的方式正確。
這是我要執行的操作的一個示例:
typedef struct Foo
{
uint32_t *bar;
} Foo
int main(void)
{
Foo *foo;
uint32_t *bar[20];
foo = (Foo *)malloc(sizeof(Foo));
*bar = malloc(sizeof(uint32_t) * 20);
for(int i = 0; i < 20; i++)
{
bar[i] = (uint32_t*)malloc(sizeof(uint32_t));
}
foo->bar = *bar;
}
編碼
uint32_t *bar[20];
將bar
聲明為20個指向uint32_t
指針的數組,這可能不是您想要的。 由於使用malloc
動態分配數組,因此應將bar
聲明為指針而不是數組:
uint32_t **bar;
您可能要考慮在單個malloc()
進行內存分配,而不是在使用分段方法。 例如,您可能要考慮做類似以下的事情。
這將分配對malloc()
的單次調用所需的內存,以便只需要對free()
的單次調用即可釋放內存。 它速度更快,並且往往使堆的碎片更少並且更易於管理。
typedef struct
{
uint32_t *bar[1]; // an array of size one that makes array syntax easy
} Foo;
Foo *FooCreateFoo (unsigned int nCount)
{
// create an array of pointers to uint32_t values along with the
// memory area for those uint32_t data values.
Foo *p = malloc (sizeof(uint32_t *) * nCount + sizeof(uint32_t) * nCount);
if (p) {
// we have memory allocated so now initialize the array of pointers
unsigned int iLoop;
uint32_t *pData = p->bar + nCount; // point to past the last array element
for (iLoop = 0; iLoop < nCount; iLoop++) {
// set the pointer value and initialize the data to zero.
*(p->bar[iLoop] = pData++) = 0;
}
}
return p;
}
int main(void)
{
Foo *foo = FooCreateFoo (20);
if (! foo) {
// memory allocation failed so exit out.
return 1;
}
// ... do things with foo by dereferencing the pointers in the array as in
*(foo->bar[1]) += 3; // increment the uint32_t pointed to by a value of 3
free (foo); // we be done with foo so release the memory
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.