c - 内存指针和数组

标签 c

我有这个结构:

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/

相关文章:

c - 为什么用函数修改二维数组不起作用?

c - 严格的别名规则真的是 "two-way street"吗?

c - C 中质量最好的抖动库

c - 如何使用指向数组的指针访问 3-d 数组

c - 可变参数加法函数 C

C:字符串、数组和指针?阵列故障?

c - 我如何创建一个包含 'Signature Algorithm' 的证书文件使用 openssl api

c - "if"和 "else"之间的执行速度是否不同?

c - flexible array member not at end of struct错误的原因是什么?

c++ - 如何读取大量数字?