C 中结构的 malloc(从 C++ 移植)

malloc of a structure in C ( ported from C++ )

我想在堆上保留一些内存 space 并用指针访问它。

代码 运行 在 C++ 中很好,但我无法在 C 中编译它。

#include <string.h>
#include <stdlib.h>

#define IMG_WIDTH 320

struct cluster_s
{
  uint16_t size;
  uint16_t xMin;
  uint16_t xMax;
  uint16_t yMin;
  uint16_t yMax;
};

static struct cluster_s* detectPills(const uint16_t newPixel[])
{

  static struct cluster_s **pixel = NULL;
  static struct cluster_s *cluster = NULL;

  if(!pixel){
    pixel = (cluster_s**) malloc(IMG_WIDTH * sizeof(struct cluster_s*));
    if(pixel == NULL){
      return NULL;
    }
  }
  if(!cluster){
    cluster = (cluster*) malloc((IMG_WIDTH+1) * sizeof(struct cluster_s));
    if(cluster == NULL){
      return NULL;
    }
    for(int i=0; i<IMG_WIDTH;i++){
      memset(&cluster[i], 0, sizeof(cluster[i]));
      pixel[i] = &cluster[i];
    }
  }
(...)
}

这给了我以下编译错误:

错误:'cluster_s'未声明(首次在此函数中使用) 像素 = (cluster_s**) malloc(IMG_WIDTH * sizeof(struct *cluster_s));

如果我注释掉这两个 malloc 调用,我就可以编译它。 我还尝试删除 malloc 之前的强制转换并得到编译错误:

在函数中_sbrk_r': sbrkr.c:(.text._sbrk_r+0xc): undefined reference to_sbrk' collect2:错误:ld 返回了 1 个退出状态

编辑: 建议的答案是正确的,问题来自未找到 sbrk

的链接器

替换

struct cluster_s
{
   ...
};

typedef struct cluster_s 
{
    ....
}cluster_s;

在 C++ 中,结构和 Class 是类似的,并且在大多数情况下可以互换使用。所以cluster_sstruct cluster_s都可以用

在 C 中,cluster_s 未定义。上面的更改将定义一个同名的类型。

关于 class 和结构的区别,您可以查看答案 When should you use a class vs a struct in C++?

这个

I also tried to remove the cast before malloc and got the compilation error:

还有这个

The code run fine in C++ but I cannot compile it in C.

自相矛盾

第一个表示您正在尝试将程序编译为 C++ 程序。

要使程序编译为 C++ 程序和 C 程序,有两种方法。

第一个在程序中到处都是使用类型说明符 struct cluster_s 而不仅仅是 cluster_s 。例如

pixel = (struct cluster_s**) malloc(IMG_WIDTH * sizeof(struct cluster_s*));
         ^^^^^^^^^^^^^^^^  
//...
cluster = (struct cluster*) malloc((IMG_WIDTH+1) * sizeof(struct cluster_s));
           ^^^^^^^^^^^^^^

第二个是为类型说明符引入别名struct cluster_s like

typedef struct cluster_s cluster_s;