c - 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 的链接器
解决方案
这个
我还尝试在 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;
推荐阅读
- xamarin - Xamarin.Forms iOS IdentityServer4 登录重定向问题
- jenkins - 是否可以通过解析/接收来自 Git/Gerrit Replica/Slave 服务器的事件来触发 Jenkins 的作业?
- vuejs2 - DOM 在 GET 请求完成之前加载计算属性,如何延迟?
- javascript - 为什么 js 中的 console.log(window) 不能在常规 Visual Studio 的控制台上运行?
- javascript - Electron TrayIcon 在 linux 上无法正常工作
- python - 如何使 NaN 数值低于任何其他数值。在比较期间?
- php - 填充一个数组以在 Laravel 中插入该数组的值
- sql - 将具有小时(数据类型编号)和分钟(数据类型编号)的两个单独的列转换为时间数据类型并在 oracle 中减去 90 分钟
- r - 如何通过 ggplot2 用两个不同的 scales_fill_gradient 覆盖两个热图?
- javascript - 为什么发送AJAX请求的函数生成表单后,JS生成的表单会立即触发AJAX请求。一定要 onsubmit 事件吗?