基于这个答案:https://stackoverflow.com/a/19765782/1606345
#include <stdlib.h>
typedef struct {
int *arr1;
int *arr2;
} myStruct;
myStruct *allocMyStruct(int num)
{
myStruct *p;
if ((p = malloc(sizeof *p +
10 * sizeof *p->arr1 +
10 * num * sizeof *p->arr2)) != NULL)
{
p->arr1 = (int *)(p + 1);
p->arr2 = p->arr1 + 10;
}
return p;
}
void initMyStruct(myStruct * a, int num)
{
int i;
for (i = 0; i < 10; i++) a->arr1[i] = 0;
for (i = 0; i < 10 * num; i++) a->arr2[i] = -1;
}
int main (void)
{
int num = 3;
myStruct *a = allocMyStruct(num);
initMyStruct(a, num);
free(a);
return 1;
}
将p->arr1
分配给(p + 1)
的地址是安全的吗?
p->arr1 = (int *)(p + 1);
在如何考虑结构分配方面,您有一个基本问题。当你对结构进行malloc时,你会malloc该结构的大小,你不会malloc它将包含的数组,这些数组需要单独分配。为此,您的代码应更像:
myStruct *allocMyStruct(int num)
{
myStruct *p = malloc( sizeof( myStruct ) );
if( p != NULL )
{
p->arr1 = malloc( sizeof( int ) * 10 ); // p->arr1 now points to an array of 10 elements
p->arr2 = malloc( sizeof( int ) * 10 * num ); // p->arr2 now points to an array of 10 * num elements
}
return p;
}
请记住,当您释放它时,您还需要单独释放数组,因此如果您的指针a
myStruct :
free( a->arr1 );
free( a->arr2 );
free( a );