I would like to reserve some memory space on the heap and access it with a pointer.
The code run fine in C++ but I cannot compile it in 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];
}
}
(...)
}
which gives me the following compilation error:
error: 'cluster_s' undeclared (first use in this function) pixel = (cluster_s**) malloc(IMG_WIDTH * sizeof(struct *cluster_s));
If I comment out the two malloc calls, I am able to compile it. I also tried to remove the cast before malloc and got the compilation error:
In function _sbrk_r':
sbrkr.c:(.text._sbrk_r+0xc): undefined reference to
_sbrk'
collect2: error: ld returned 1 exit status
EDIT: The proposed answers are correct, the problem comes from the linker which do not find sbrk