首页 > 解决方案 > C 中结构的 malloc(从 C++ 移植)

问题描述

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

代码在 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”未声明(在此函数中首次使用)pixel = (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 的链接器

标签: cstructcastingmalloctypedef

解决方案


这个

我还尝试在 malloc 之前删除强制转换并得到编译错误:

和这个

代码在 C++ 中运行良好,但我无法在 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例如

typedef struct cluster_s cluster_s;

推荐阅读