-2
char ** ptr = new char *[3];
ptr[0] = new char [5];
ptr[1] = new char [6];
ptr[2] = new char [7];

cout<<"Enter first array: ";
cin.getline(ptr[0], 5);
cin.getline(ptr[1], 6);
cin.getline(ptr[2], 7);
for (int i=0; i<3; i++){
    cout<<ptr+i<<endl;
}
for (int i=0; i<3; i++){
    delete[] ptr[i];
}

When I run this code, it gives the following output:

    Enter first array: name
    0xf99c20
    0xf99c28
    0xf99c30

I actually wanted the user input printed out.

Could someone please tell me how to do this?

Yurets
  • 3,999
  • 17
  • 54
  • 74
  • 1
    Err... Solution to? – WhiZTiM Feb 07 '17 at 07:56
  • 1
    You probably wanted to print `ptr[i]` which is same as `*(ptr+i)`. BTW, despite your last `delete[]..` in a loop, you still have a leak. Prefer `std::string` for your string needs and `std::vector` for your array needs – WhiZTiM Feb 07 '17 at 07:59
  • 1. Solution to what??? 2. You need to `delete[] ptr` at the end of your code. 3. You may as well declare `char* ptr[3]` (instead of allocating it and deleting it). 4. There are much simpler, better and more correct ways of doing whatever it is you're trying to do. – barak manos Feb 07 '17 at 08:02

2 Answers2

0

The type of ptr+i is char**, not char*, so is just being printed as a pointer. To have it print as a string, use ptr[i], which is a char*.

That said, use a std::vector<std::string>. Then you can use the string version of std::getline. Then you avoid many possible problems with matching up new and delete, leaks, dealing with longer user input, dealing with a different number of lines of user input, etc.


Also, please reconsider your use of what are often considered bad practices: using namespace std; and endl (those are links to explanations).

Community
  • 1
  • 1
BoBTFish
  • 19,167
  • 3
  • 49
  • 76
  • 2
    @MuhammadIbrahim if this is the solution to your problem you should accept the answer... – W.F. Feb 07 '17 at 08:22
0

you have logic misunderstanding of pointer concept when you print ptr+i it will give you the actual address locations of your inputs in the memory

to print the value of pointer you can use:

*(ptr+i)

or :

ptr[i]

also getline (char* s, streamsize n ); max stream size of your inputs should be bigger because there is a null character '\0' at the end of each character sequences and newline character '\n' when you enter another input:

cin.getline(ptr[0], 10);
cin.getline(ptr[1], 10);
cin.getline(ptr[2], 10);

link to the solution: https://ideone.com/maSOSs

Oghli
  • 2,200
  • 1
  • 15
  • 37