簡體   English   中英

從C中的函數返回二維數組

[英]Returning a 2d array from a function in C

我試圖從一個函數返回一個二維數組,但是由於某種原因,當我在主函數中調用該函數時,它會導致分段錯誤。

char **upper_case_word(char **word,int size){
        int i =0;
        int i2=0;
        // this gets the number of words
        int length = upper_counter(word,size);
        //this gets the size of the largest word
        int size2 = length_upper(word,size);

        char ** upper =malloc(length*sizeof(char*));

        for(i =0; i <length; i++){
                upper[i]= malloc(size2*sizeof(char*));
        }
        i =0;

        for(i =0; i<=size2; i++){

                for(i2 =0; i2<(sizeof(word[i])/sizeof(word[i][0])); i2++){   
                             if(isupper(word[i][i2])!=0){     
                                upper[i]=word[i];
                        }
                }
        }
        return upper;
}
int main(){
   //this is causing the segmentation fault.
   char ** upper = upper_case_word(words,size);

 return(0);
}

我不確定這是否涵蓋所有問題,但以下是一些問題:

您分配的不是2D數組。 而是分配一個指針數組,並為每個指針分配一個數組。 最后一個數組應該是char數組。 但是,您的代碼是:

upper[i]= malloc(size2*sizeof(char*));
                              ^^^^^
                              Should be char, not char*

但這不是seg錯誤的原因-它只是分配了比所需更多的內存。

外部數組(即upper )使用如下length分配:

char ** upper =malloc(length*sizeof(char*));
                      ^^^^^^

但稍后您使用size2對其進行迭代-此處:

    for(i =0; i<=size2; i++){

因此,如果size2大於或等於length ,則將超出范圍。 這可能會導致段故障。

然后這部分:

sizeof(word[i])/sizeof(word[i][0])

您確定正在做您想要的嗎?

它與:

sizeof(char*)/sizeof(char)

要不就

sizeof(char*)

我懷疑那是你想要的。

然后,您有以下代碼:

                    if(isupper(word[i][i2])!=0){     
                        upper[i]=word[i];
                    }

在這里,您可以更改upper[i]持有的指針值。 那是沒有意義的,這是內存泄漏,因為您用另一個指針覆蓋了指向動態分配內存的指針。

暫無
暫無

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

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