【发布时间】:2019-07-30 09:37:57
【问题描述】:
我想在堆上保留一些内存空间并用指针访问它。
代码在 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];
}
}
(...)
}
这给了我以下编译错误:
error: 'cluster_s' undeclared (第一次在这个函数中使用) 像素 = (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 的链接器
【问题讨论】:
-
(cluster_s*)==>(struct cluster_s*)但在 C 语言中,无论如何你都不应该需要演员表。如果您在删除强制转换后出现编译错误,那么它不是 C 编译器,可能文件是 .cpp。 -
添加 (struct cluster_s*) 给了我同样的错误,我没有强制转换。即:在函数_sbrk_r'中:sbrkr.c:(.text._sbrk_r+0xc): undefined reference to_sbrk' collect2: error: ld returned 1 exit status
-
您也必须在另一行更改
(cluster_s**)。 -
是的,我也这样做了。
标签: c struct casting malloc typedef