PedroCunha_67677
PedroCunha_67677

Reputation: 47

Memory Pointers and Arrays

I have this struct:

struct table{
    int miny,maxy,maxa;
    int** list;
};

and its subsequent typedef:

typedef struct table *StatTable;

So, my doubt is the following:
On the initialisation of a struct table I do this and it might work fine:

StatTable newStatistic(int min,int max,int maxauts){
    StatTable aux=malloc(sizeof(StatTable));
    aux->miny=min;
    aux->maxy=max;
    aux->maxa=maxauts;
    aux->list=calloc(((max-min))*(maxauts+1),sizeof(int));
    return aux;
}

Since I declared that list as an int ** can I implement a function this way?

int get(StatTable st,int ano,int nAut){
    return st->list[ano-getMinYear(st)][nAut];
}

Upvotes: 0

Views: 84

Answers (2)

netcoder
netcoder

Reputation: 67695

This:

StatTable aux=malloc(sizeof(StatTable));

...is wrong. You're allocating the size of a pointer to aux. You should allocate the size of the structure instead:

StatTable aux=malloc(sizeof(struct table));

Instead allocating one contiguous block of memory like this:

 aux->list=calloc(((max-min))*(maxauts+1),sizeof(int));

...you should allocate your 2D pointers like this:

aux->list = calloc(max - min, sizeof(*aux->list));
for (int i=0; i<max-min; i++)
    aux->list[i] = calloc(maxauts + 1, sizeof(**aux->list));

Upvotes: 0

LearningC
LearningC

Reputation: 3162

StatTable aux=malloc(sizeof(StatTable));

This statement will not create an variable of struct table. StatTable is a typedef for a pointer to the struct variable so sizeof(StatTable) gives size of a pointer so this statement wont allocate space for a variable of structure.
Therefore

aux->miny=min;
aux->maxy=max;
aux->maxa=maxauts

these statements results in segmentation fault since memory is not allocated for them.

To create a variable and then to make aux a pointer to it use,

 StatTable aux=malloc(sizeof(struct table));

Upvotes: 2

Related Questions