C - 'char **' differs in levels of indirection from 'char (*)[6]'

前端 未结 3 1144
说谎
说谎 2021-01-02 01:31

Can someone please explain to me what\'s wrong with the following, and more importantly why?

int main( int argc, char *argv[] )
{
    char array[] = \"array\         


        
相关标签:
3条回答
  • 2021-01-02 01:47

    This would be the way to do what you seem to be trying to do:

    int main( int argc, char *argv[] )
    {
      char array[] = "array";
      char (*test)[6];
      test = &array;
    
      (*test)[0] = 'Z';
    
      printf( "%s\n", array );
    
      return 0;
    }
    

    test is a pointer to an array, and an array is different from a pointer, even though C makes it easy to use one like the other in my cases.

    If you wanted to avoid having to specify a specific sized array, you could use a different approach:

    int main( int argc, char *argv[] )
    {
      char array[] = "array";
      char *test;
      test = array;  // same as test = &array[0];
    
      test[0] = 'Z';
    
      printf( "%s\n", array );
    
      return 0;
    }
    
    0 讨论(0)
  • 2021-01-02 01:52

    char **test; is a pointer to a pointer, but if you're going to take the address of an entire array then it needs to be a pointer to entire array i.e char (*test)[6];

    0 讨论(0)
  • 2021-01-02 01:57

    test = &array

    is wrong because test is of type char** and &array is a char(*)[6] and is a different type from char**

    An array isn't the same type as char* although C will implicitly convert between an array type and a char* in some contexts, but this isn't one of them. Basically the expectation that char* is the same as the type of an array (e.g: char[6]) is wrong and therefore the expectation that taking the address of an array will result in a char** is also wrong.

    0 讨论(0)
提交回复
热议问题