1

基于这个答案: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);
4

1 回答 1

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

请记住,当您释放它时,您还需要单独释放数组,因此如果您的指针 myStruct 是a

free( a->arr1 );
free( a->arr2 );
free( a );
于 2013-11-04T13:22:06.093 回答