簡體   English   中英

二維數組分割錯誤的結構寫

[英]Struct with 2d array segmentation fault's on writing

過去一天,我在使用此功能時遇到了麻煩,在網站上搜索類似的問題並沒有幫助。

我正在嘗試初始化包含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),因此仍然存在問題。

但是現在沒有分段錯誤(當它試圖向數組寫入多個數字時,至少不會出現在程序的這一部分中,盡管還有一段距離)。

再次查看您的“內部”分配,在此分配給cod.blocks[width] ,它超出范圍,將導致未定義的行為

我確定您的意思是在那里分配給cod.blocks[i]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM