c++ - 函数的返回值是二位数组,怎么写
PHPz
PHPz 2017-04-17 13:52:12
0
4
542
 char str[100][60] = {0};// 全局变量

char** fun( ) {
    
    ......
    return str;   
}

返回值部分怎么写?

PHPz
PHPz

学习是最好的投资!

reply all(4)
黄舟

You are asking how to write the return value type:

char str[100][60];
typedef char (*str60)[60];

str60 func(){ return str;}

or:

char str[100][60];

char** func(){ return (char **)str;}

It depends on your requirements.
The reason is that the type of str is actually str60, so when str[1][2] is used, the compiler will know that the accessed address is the byte pointed to by str+60*1+2 data (char type). This is not the same type as char**, and char ** does not contain information 60.

So to change it to legal C code, you need to change the type of the return value or force type conversion.

Ty80

Remember to let the caller know the length of the array when returning char**, because the length information of the array is lost when char[] degenerates into char*. It is recommended to add an int* table length to the parameter.

迷茫

It is better to follow the method above:

char** func(int* size1, int* size2) {}
黄舟
char* fun( ) {

    char* p = str[0][0];
    // do something
    for( int i = 0;i < 100 ; ++i ) 
       for ( int j = 0; j< 60; ++j )
            *(p + 100 * i + j ) = 'a'
   
    return p;   
}

The example is very rough. In fact, it must return the object created on the heap, not the stack.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template