AlwaysWin AlwaysWin - 1 month ago 12
C Question

How to access a two-dimensional array in a structure using a structure pointer in a function?

I'm new here, so forgive my mistakes. I'm clearly not familiarized with pointers nor structure, in general, I'm not the best programmer either. But anyways, I'm hoping someone can help me out here.

I'm trying to allocate space for the "2-d array [tag]" variable in my structure in "func." I can't seem to get any of the assignments to work, due the bad referencing of "tag." Here's the errors being produced:

prog.c: In function ‘func’:
prog.c:33: error: assignment makes integer from pointer without a cast
prog.c:38: error: subscripted value is neither array nor pointer
prog.c:39: error: subscripted value is neither array nor pointer


Thanks in advance!

// prog.c
struct Str
{
unsigned int s;
unsigned int e;
unsigned long int tag;
};


void func(struct Str *str)
{
str->tag = malloc(str->s * sizeof(unsigned long int *)); // 33 str->tag error

int i;
for (i = 0; i < str->s; i++)
{
str->tag[i] = malloc(str->e * sizeof(unsigned long int)); // 38 str->tag[i] error
memset(str->tag[i], -1, str->e * sizeof(unsigned long int)); // 39 str->tag[i] error
}
}

Answer

Just make your tag a double pointer:

struct Str
{
    unsigned int s;
    unsigned int e;
    unsigned long int** tag;
};
Comments