结构与写入时的2d阵列分段错误

时间:2015-12-14 12:55:21

标签: c arrays struct segmentation-fault

过去一天我在使用此功能时遇到了问题,并且在网站上搜索类似的问题并没有帮助。

我正在尝试初始化包含2d数组的结构。因此,程序编译正常并且从数组中读取没有问题,但每次尝试写入数组时都会导致分段错误。

这是有问题的结构:

typedef struct {
    pgm_format_t format;
    unsigned int width;
    unsigned int height;
    unsigned int block_width;
    unsigned int block_height;
    unsigned int max_value;
    unsigned short **blocks;
} cod_t;

这就是功能:

cod_t cod_create(pgm_format_t format, unsigned int width, unsigned int height){

cod_t cod;
unsigned short i;

if((cod.blocks=calloc(width,sizeof(unsigned short *)))==NULL){

printf("nope 1\n"); //no problem
}

for(i=0;i<width;i++){
    if((cod.blocks[width]=calloc(height,sizeof(unsigned short)))==NULL){
        printf("nope 2\n"); //no problem
    }
}
int f=cod.blocks[0][0]; //no problem
printf("%d",f); //writes a wierd number, probably because it's never been assigned

cod.blocks[0][0]=3; //segmentation fault
printf("%d",cod.blocks[0][0]);

return cod;
}

我在这里做错了什么?

编辑:

好吧,看来我在第二个calloc中犯了一个新手错误。然而,即使有了

    if((cod.blocks[i]=calloc(height,sizeof(unsigned short)))==NULL){

第二个printf打印的东西不是3(在我的情况下,031280),所以这还有一些问题。

现在没有分段错误(至少在程序的这一部分中,尽管还有一个,当它试图向数组写入多个数字时)。

1 个答案:

答案 0 :(得分:1)

看看你的内心&#34;再次分配,您指定的cod.blocks[width],这是超出界限,将导致未定义的行为

我确定你的意思是指定cod.blocks[i]