我有这个结构:
struct table{
int miny,maxy,maxa;
int** list;
};
及其后续的 typedef:
typedef struct table *StatTable;
所以,我的疑问如下:
在 struct table
的初始化中,我这样做了,它可能工作正常:
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;
}
既然我将该列表声明为一个 int **,我可以用这种方式实现一个函数吗?
int get(StatTable st,int ano,int nAut){
return st->list[ano-getMinYear(st)][nAut];
}
最佳答案
StatTable aux=malloc(sizeof(StatTable));
此语句不会创建struct table
的变量。 StatTable
是指向结构变量的指针的 typedef
,因此 sizeof(StatTable)
给出了指针的大小,因此该语句不会为结构变量。
因此
aux->miny=min;
aux->maxy=max;
aux->maxa=maxauts
这些语句导致段错误
,因为没有为它们分配内存。
要创建一个变量,然后使 aux
成为指向它的指针,
StatTable aux=malloc(sizeof(struct table));
关于c - 内存指针和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23133837/