0

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];
}
5
  • 2
    Why not compile and see for yourself? Commented Apr 17, 2014 at 13:09
  • The problem is that it's a module from a project and I'm seg faulting... Just to know if is this the cause... Commented Apr 17, 2014 at 13:11
  • if you have seg fault and you've narrowed it down to the get() function, my guess is that your'e accessing out of the list range. i.e there is no item at list[x][y], you should validate the index before using []. Commented Apr 17, 2014 at 13:13
  • it will compile. But runtime error(seg fault) depends on what pointer it holds. Commented Apr 17, 2014 at 13:15
  • So, for example to prevent the seg fault, I can put an if clause? Commented Apr 17, 2014 at 13:21

2 Answers 2

2
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));
Sign up to request clarification or add additional context in comments.

Comments

0

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.