【问题标题】:Using malloc on double pointers inside在内部的双指针上使用 malloc
【发布时间】:2015-10-29 03:27:25
【问题描述】:

我有一个这样编码的结构...

typedef struct {
    double* xcoords;
    double* ycoords;
    char name[128];
    int numOfCoords;
} Image;

我使用 Image* 在堆上为 32 个图像的数组动态分配内存。

Image* imgPointer;
imgPointer = malloc(32 * sizeof(Image));

我打算在图像中的 double* xcoords 和 ycoords 上使用 malloc 来创建一个包含 32 个双精度数的数组,但我很难弄清楚如何去做。

这应该有效吗?我是 C 新手,指针/结构的关系令人困惑......

// Set up arrays and increment pointer to the next struct
imgPointer->xccords = malloc(32 * sizeof(double));
imgPointer->ycoords = malloc(32 * sizeof(double));
imgPointer++;

【问题讨论】:

  • 为什么是malloc(32 * sizeof(double)) 而不是typedef struct { double xcoords[32]; double ycoords[32]; char name[128]; int numOfCoords; } Image; 如果总是32 ...
  • 这行得通,但不要 ++ imgPointer 本身。相反,设置Image *tmp = imgPointer,然后设置tmp->xcoords = ... ,以此类推,最后设置tmp++。这样,您将保留一个指向您已分配的原始 imgPointer 数组的指针。
  • 我实际上无法对 32 个元素进行硬编码。 struct 数组和 struct 内部的数组必须能够通过在满时调用 realloc 来保持增长。
  • 是的,它有效,但你的目标不明确,所以你可能会得到意想不到的结果。请在问题中包含您的目标。
  • 推荐而不是pointer = malloc(N * sizeof(*pointer_type));,使用pointer = malloc(sizeof *pointer * N);(sizeof 变量与sizeof 类型)更易于维护,代码出错的机会更少。

标签: c arrays pointers struct


【解决方案1】:

你有:

// Set up arrays and increment pointer to the next struct
imgPointer->xccords = malloc(32 * sizeof(double));
imgPointer->ycoords = malloc(32 * sizeof(double));
imgPointer++;

这会导致问题。

问题1:您没有为所有Images 的内部数据分配内存。您只为第一个Image 的内部数据分配了内存。

问题 2: 你改变了指针的值。它不指向malloc 返回的内存。在更改的指针值上调用 free 将导致未定义的行为。不调用free 会导致内存泄漏。

一个解决方案

// Allocate memory for the internal data of the Images
for ( int i = 0; i < 32; ++i )
{
   imgPointer[i].xccords = malloc(32 * sizeof(double));
   imgPointer[i].ycoords = malloc(32 * sizeof(double));
}

使用完对象后,释放内存。

// Free the internal data of the Images
for ( int i = 0; i < 32; ++i )
{
   free(imgPointer[i].xccords);
   free(imgPointer[i].ycoords);
}

// Free the array of Images
free(imgPointer);

更清洁的解决方案

由于内部数据是 32 个双精度数组,因此可以将结构更改为

typedef struct {
    double xcoords[32];
    double ycoords[32];
    char name[128];
    int numOfCoords;
} Image;

那么,就不需要使用malloc为它们分配内存,也不需要使用free来释放内存了。

你也可以创建一个Images 的数组,因为你知道大小。

Image images[32];

那么,就不需要使用malloc来创建Images的数组,也就不需要free分配的内存了。

【讨论】:

  • @ColinSpencely . 会起作用,因为images[0] 不是指针而是结构变量。
猜你喜欢
  • 2016-06-16
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
  • 2012-04-29
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 2017-08-09
相关资源
最近更新 更多