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

前端 未结 3 1183
说谎
说谎 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;
    }
    

提交回复
热议问题