简体   繁体   English

从C中的函数返回二维数组

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

I am trying to return a 2d array from a function but for some reason when I call the function in my main it causes a segmentation fault. 我试图从一个函数返回一个二维数组,但是由于某种原因,当我在主函数中调用该函数时,它会导致分段错误。

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);
}

I'm not sure this covers all problems but here a few to start with: 我不确定这是否涵盖所有问题,但以下是一些问题:

What you allocate is not a 2D array. 您分配的不是2D数组。 Instead you allocate an array of pointers and for each of these pointer, you allocate an array. 而是分配一个指针数组,并为每个指针分配一个数组。 That last array should be an array of char. 最后一个数组应该是char数组。 However, your code is: 但是,您的代码是:

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

But that is not the cause of the seg fault - it's just allocating more memory than needed. 但这不是seg错误的原因-它只是分配了比所需更多的内存。

The outer array, ie upper is allocated using length like: 外部数组(即upper )使用如下length分配:

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

but later you iterate it using size2 - here: 但稍后您使用size2对其进行迭代-此处:

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

So in case size2 is greater than or equal to length , you access out of bounds. 因此,如果size2大于或等于length ,则将超出范围。 That may cause a seg fault. 这可能会导致段故障。

Then this part: 然后这部分:

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

Are you sure that is doing what you want? 您确定正在做您想要的吗?

It is the same as: 它与:

sizeof(char*)/sizeof(char)

or just 要不就

sizeof(char*)

I doubt that is what you want. 我怀疑那是你想要的。

Then you have this code: 然后,您有以下代码:

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

Here you change the pointer value held by upper[i] . 在这里,您可以更改upper[i]持有的指针值。 That makes no sense and it's a memory leak because you overwrite a pointer that points to dynamic allocated memory with another pointer. 那是没有意义的,这是内存泄漏,因为您用另一个指针覆盖了指向动态分配内存的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM