1

I have the following code

#include <iostream>
#include <typeinfo>
using namespace std;
class myClass{
     public:
      myClass(){
        cout<<"constructor called..."<<endl; }
};

int main(){
   myClass ** p1;
   myClass *p2[5];

   *(p2+4) = new myClass;
   *p1 = new myClass;  // "constructor called..." printed, but segmentation fault

   cout<<typeid(p1).name()<<endl; 
   // "PP7myClass" printed, after commenting out *p1 = new myClass;
   // what is PP7?
   cout<<typeid(2).name()<<endl; 
   // "A5_P7myClass" printed, after commenting out *p1 = new myClass; 
   //  what is A5_P7?

   if(typeid(p1)==typeid(p2)) cout<<"==="<<endl; 
   if(typeid(p1)==typeid(*p2)) cout<<"&&&"<<endl;
   // I expected at least one of the above cout 
   // two lines should be printed, but nothing printed actually, why?


   return 0;
   }
  1. why there is segmentation fault after calling the constructor for p1?
  2. If the line *p1 = new myClass; is commented out, "PP7myClass" and "A5_P7myClass" printed, what are "PP7" and "A5_P7"?
  3. If I define a function void func(myClass a, myClass b){} and then do func(p1, p2);, the compiler will complain that can not convert myClass ** to myClass for two arguments, so that means p1 and p2 are both of type myClass **, but why for the two lines above return 0;, nothing is printed?
Allanqunzi
  • 3,230
  • 1
  • 26
  • 58

2 Answers2

2

why there is segmentation fault after calling the constructor for p1?

myClass ** p1;

says "gimme space for a pointer to a pointer"; not "gimme space at the point that this unitialized pointer points to, too".

    2.

they are typeids.

3.

You don't initialize pc or p to be something: I wonder why your compiler doesn't stop you from doing this, but it seems pc has neither type of p nor of *p.

EDIT:

after your edit: The typeids of a pointer and an array aren't the same.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
2
  1. p1 itself doesn't actually point at something. So *p1 dereferences uninitialized memory

  2. They are name-mangled names of the types, as constructed by the compiler. See http://en.wikipedia.org/wiki/Name_mangling

  3. I don't see a pc variable or type defined/declared in your code. EDIT Because the prototype of f() calls for parameters of type myClass to be passed. p2 is of type myClass** too; it is the name of an array of pointers to myClass and degenerates to type myClass**, see standard conversions: Array-to-pointer conversion

Community
  • 1
  • 1
emvee
  • 4,371
  • 23
  • 23
  • 3, my bad, just changed. – Allanqunzi Mar 15 '15 at 19:37
  • 1. If I do `myClass * p1; p1 = new myClass;`, this works fine. 3. I understand the degeneration of array to pointer, but didn't realize that this happens before the array is passed to inside the function body. – Allanqunzi Mar 15 '15 at 19:49