search

Home  >  Q&A  >  body text

c++ - 函数的返回值是二位数组,怎么写

 char str[100][60] = {0};// 全局变量

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

返回值部分怎么写?

PHPzPHPz2807 days ago547

reply all(4)I'll reply

  • 黄舟

    黄舟2017-04-17 13:54:12

    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.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:54:12

    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.

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:54:12

    It is better to follow the method above:

    char** func(int* size1, int* size2) {}

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:54:12

    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.

    reply
    0
  • Cancelreply