结构体中数组和结构体的 Malloc

发布于 2024-10-26 21:32:08 字数 215 浏览 3 评论 0原文

一个如何 malloc 一个位于另一个结构内部的结构?

我还想在结构内分配一个项目数组,然后在需要时重新分配该数组,这是如何正确完成的?

您能否给出一个声明结构的示例,然后是上面的内容。

我有点不确定事情的顺序。

结构体中的数组是否会被释放,然后结构体本身是否会被释放?结构体在创建时是否必须进行 malloc,然后对其字段进行 malloc/声明等?

How does one malloc a struct which is inside another struct?

I would also like to malloc an array of items inside a struct and then realloc this array when needed, how is this done correctly?

Could you please give an example of declaring a struct and then the above.

Im a little unsure of the order of things.

Would the array within a struct be freed and then the struct itself, must the struct be malloced when it is created and then its fields be malloced/declared etc?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

沐歌 2024-11-02 21:32:08

包含在另一个 struct 内的 struct 是通过副本包含的,因此您不必单独对其进行 malloc。如果struct包含指向另一个struct的指针,那么您可以考虑为其动态分配内存。

struct Point2d
{
    float x;
    float y;
};

struct Rect
{
    struct Point2D a;
    struct Point2D b;
};

struct LinkedListNode
{
    struct LinkedListNode* next;
    int value;
};

struct Rect中,struct Point2D元素被插入到struct Rect中,您不必为它们动态分配内存。相反,在 struct LinkedListNode 中,下一个元素由指针引用,并且必须动态分配内存。

两个版本都有用,看情况。管理内存没有正确的方法,这取决于您的使用情况。

同样的情况也发生在数组的情况下。如果您的数组是静态大小的,那么它可以直接包含在struct中。但是,如果大小可能变化,则必须在struct 中存储一个指针。

struct Header
{
    char magic[4];
    unsigned int width;
    unsigned int height;
};

struct Buffer
{
    char* data;
    unsigned int size;
    unsigned int capacity;
};

struct Buffer* buffer_init()
{
    struct Buffer* buffer = (struct Buffer*)malloc(sizeof(struct Buffer));
    buffer->data = 0;
    buffer->size = 0;
    buffer->capacity = 0;
}

void buffer_grow(struct Buffer* buffer, size_t capacity)
{
    if (capacity > buffer->capacity)
    {
        buffer->data = realloc(buffer->data, capacity);
        buffer->capacity = capacity;
    }
}

void buffer_append(struct Buffer* buffer, const char* data, unsigned int dataLen)
{
    if (dataLen + buffer->size > buffer->capacity)
        buffer_grow(MAX(dataLen + buffer->size, buffer->capacity * 2));

    memcpy(buffer->data + buffer->size, data, dataLen);
    buffer->size += dataLen;
}

realloc函数只进行浅拷贝,即复制指针值,但不复制指向的对象。再说一次,你如何处理它取决于你的应用程序。

A struct included inside another struct is contained by copy, so you would not have to separately malloc it. If the struct contains a pointer to another struct, then you can consider allocating memory for it dynamically.

struct Point2d
{
    float x;
    float y;
};

struct Rect
{
    struct Point2D a;
    struct Point2D b;
};

struct LinkedListNode
{
    struct LinkedListNode* next;
    int value;
};

In struct Rect, the struct Point2D element are inserted into struct Rect and you don't have to dynamically allocate memory for them. On the contrary in the struct LinkedListNode the next element is referenced by a pointer and the memory must be dynamically allocated.

The two version are both useful, depending on the situation. There is no correct way to manage memory, it'll depend on your usage.

This same situation occurs in the case of an array. If your array is statically sized, then it can be directly included in the struct. However, if the size can vary, you must store a pointer within the struct.

struct Header
{
    char magic[4];
    unsigned int width;
    unsigned int height;
};

struct Buffer
{
    char* data;
    unsigned int size;
    unsigned int capacity;
};

struct Buffer* buffer_init()
{
    struct Buffer* buffer = (struct Buffer*)malloc(sizeof(struct Buffer));
    buffer->data = 0;
    buffer->size = 0;
    buffer->capacity = 0;
}

void buffer_grow(struct Buffer* buffer, size_t capacity)
{
    if (capacity > buffer->capacity)
    {
        buffer->data = realloc(buffer->data, capacity);
        buffer->capacity = capacity;
    }
}

void buffer_append(struct Buffer* buffer, const char* data, unsigned int dataLen)
{
    if (dataLen + buffer->size > buffer->capacity)
        buffer_grow(MAX(dataLen + buffer->size, buffer->capacity * 2));

    memcpy(buffer->data + buffer->size, data, dataLen);
    buffer->size += dataLen;
}

The realloc function only does a shallow copy, that is pointer value is copied, but not the pointed object. One more time, how you deal with it will depend on your application.

笔芯 2024-11-02 21:32:08
typedef struct _A
{
  int *arr;
  int arrCount;
} A;

void Construct_A(A *a, int arraySize)
{
  a->arrCount = arraySize;
  a->arr = (int*)malloc(sizeof(int)*arraySize);
}

void Destruct_A(A *a)
{
  free(a->arr);
  a->arr = 0;
}

typedef struct _B
{
  A *a;
} B;

void Construct_B(B *b, int arraySize_A)
{
  b->a = (A*)malloc(sizeof(A));
  Construct_A(b->a);
}

void Destruct_B(B *b)
{
  Destruct_A(b->a);
  free(b->a);
  b->a = 0;
}

void main()
{
  B b;
  Construct_B(&b, 10);

  // Use b and b->a

  Destruct_B(&b);
}
typedef struct _A
{
  int *arr;
  int arrCount;
} A;

void Construct_A(A *a, int arraySize)
{
  a->arrCount = arraySize;
  a->arr = (int*)malloc(sizeof(int)*arraySize);
}

void Destruct_A(A *a)
{
  free(a->arr);
  a->arr = 0;
}

typedef struct _B
{
  A *a;
} B;

void Construct_B(B *b, int arraySize_A)
{
  b->a = (A*)malloc(sizeof(A));
  Construct_A(b->a);
}

void Destruct_B(B *b)
{
  Destruct_A(b->a);
  free(b->a);
  b->a = 0;
}

void main()
{
  B b;
  Construct_B(&b, 10);

  // Use b and b->a

  Destruct_B(&b);
}
〃安静 2024-11-02 21:32:08

以下是结构体中嵌套结构体和数组的示例。您会注意到在释放外部结构之前必须如何处理嵌套元素,否则最终会导致内存泄漏。

typedef struct Base Base;
struct Base
{
  int x;
};

typedef struct Sample Sample;
struct Sample
{
  Base base;
  int size;
  int *arr;
};

// Create the sample struct

Sample *createSample()
{
  Sample sample = malloc(sizeof(Sample));
  if(sample == NULL)
  {
    return NULL;
  }
  sample->base = malloc(sizeof(Base));
  if(sample->base == NULL)
  {
    free(sample);
    return NULL;
  }
  sample->base->x = 0;
  sample->size = 0;
  sample->arr = NULL;
  return sample;
}

// Adding element to the array

void addItemToSample(Sample *sample, int item)
{
  if(sample == NULL)
  {
    return;
  }
  int *arr = realloc(sample->arr, sizeof(int) * (sample->size + 1));
  if(arr == NULL)
  {
    return;
  }
  arr[sample->size++] = item;
  sample->arr = arr;
}

// Freeing the struct

void freeSample(Sample *sample)
{
  // Free deep elements first
  free(sample->base);
  free(sample->arr);
  // Free outer
  free(sample);
}

The following is an example of nested structs and arrays in structs. You'll notice how the nested elements must be taken care of before you free the outer struct or else you'll end up with a memory leak.

typedef struct Base Base;
struct Base
{
  int x;
};

typedef struct Sample Sample;
struct Sample
{
  Base base;
  int size;
  int *arr;
};

// Create the sample struct

Sample *createSample()
{
  Sample sample = malloc(sizeof(Sample));
  if(sample == NULL)
  {
    return NULL;
  }
  sample->base = malloc(sizeof(Base));
  if(sample->base == NULL)
  {
    free(sample);
    return NULL;
  }
  sample->base->x = 0;
  sample->size = 0;
  sample->arr = NULL;
  return sample;
}

// Adding element to the array

void addItemToSample(Sample *sample, int item)
{
  if(sample == NULL)
  {
    return;
  }
  int *arr = realloc(sample->arr, sizeof(int) * (sample->size + 1));
  if(arr == NULL)
  {
    return;
  }
  arr[sample->size++] = item;
  sample->arr = arr;
}

// Freeing the struct

void freeSample(Sample *sample)
{
  // Free deep elements first
  free(sample->base);
  free(sample->arr);
  // Free outer
  free(sample);
}
蓝戈者 2024-11-02 21:32:08

它的可读性不是很好,但有时人们会创建一个带有计数成员和最终单元素数组成员的结构。然后有一个特殊的工厂方法,它分配足够的空间,以便您可以写入对数组中的元素进行计数。显然数组成员可以是任何类型。

typedef struct {
    int count;
    int elements[1];
} int_array;

int_array* allocate_int_array(int count)
{
    int_array* mem = (int_array*)malloc(sizeof(int_array) + (count - 1) * sizeof(int));
    if (mem)
        mem->count = count;
    return mem;
}

It's not very readable but sometimes people create a structure with a count member and a final single-element array member. There then is a special factory method that allocates enough space so that you can write to count elements in the array. Obviously the array member can be of any type.

typedef struct {
    int count;
    int elements[1];
} int_array;

int_array* allocate_int_array(int count)
{
    int_array* mem = (int_array*)malloc(sizeof(int_array) + (count - 1) * sizeof(int));
    if (mem)
        mem->count = count;
    return mem;
}
澜川若宁 2024-11-02 21:32:08
typedef struct _A { int i; } A;
typedef struct _B { int j;  A a} B;

获取单个 B:

B *b = malloc(sizeof(B));

获取 B 数组:

B *b = malloc(sizeof(B) * arrayLength);
typedef struct _A { int i; } A;
typedef struct _B { int j;  A a} B;

To get a single B:

B *b = malloc(sizeof(B));

To get an array of B:

B *b = malloc(sizeof(B) * arrayLength);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文