Difference between two declarations involving a pointer and an array

后端 未结 6 1234
臣服心动
臣服心动 2020-12-18 11:45

What is the difference between int *a[3] and int (*a)[3]?

6条回答
  •  自闭症患者
    2020-12-18 11:55

    If you have any doubt, using this g++ trick is often handy:

    #include 
    
    template < class T > void describe(T& )
    {
      // With msvc, use __FUNCSIG__ instead
      std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
    
    int main(int argc, char* argv[])
    {
      int *a[3];
      describe(a);
    
      int (*b)[3];
      describe(b);
    
      return EXIT_SUCCESS;
    }
    

    Compile it with g++ and run it, you'll get:

    void describe(T&) [with T = int*[3]]
    void describe(T&) [with T = int (*)[3]]
    

    So, they are definitely NOT the same ! What you have is:

    1. an array of 3 pointers to int.
    2. a pointer to an array of 3 ints.

提交回复
热议问题