0

I know this is a very basic question but I am not getting it right.

char * data = new char[5];
data = "hamz";

Here I created a pointer to char, data. Data is a pointer and it stores the address of a char array on heap.

When I cout<<data;

Why does it not show me address? It shows me "hamz".

Same with this

cout<<&data[0];

How could I know the address which is stored in data? As it stores the address of the array on heap.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 6
    `data = "hamz";`and now you leaked memory. Use std::string, get a good C++ book. –  Nov 23 '17 at 16:39
  • 1
    `data = "hamz"` assigns the address of the string literal `"hamz"` to your variable `data`. The original address to the memory allocated by `new` is lost. Your compiler should've also warned you about assigning a pointer of a string literal (which is read-only) to a non-`const` pointer. – Daniel Kamil Kozar Nov 23 '17 at 16:39
  • 1
    `data = "hamz";` is just wrong. If you can't see why, then read [a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jesper Juhl Nov 23 '17 at 16:42
  • Why are you even using `new` here? Why not just a `std::string`? – Jesper Juhl Nov 23 '17 at 16:53
  • I know i can use string here. But I m just curious why data cannot show what is actually stored in it? The address of the memory on heap. @jesper – Hamza Farooqi Nov 23 '17 at 17:11

3 Answers3

3

The ostream overload of << for const char* works in a special way: it outputs the memory as characters up to the next NUL-terminator.

If you want to switch this behaviour off, and output the actual address of the pointer, then cast to const void*:

std::cout << (const void*)(data);

Note that you should really write

const char* data = "hamz";

and bin the new. Currently you leak memory like a colander leaks water.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

You can use the std::cout's member function call syntax to output the data pointer value instead of a string literal:

std::cout.operator<<(data);

This will call the 7th std::basic_ostream::operator<< overload that accepts the parameter of type const void*. Prefer std::string to raw character arrays.

Ron
  • 14,674
  • 4
  • 34
  • 47
0

First, just to answer your question, you need to cast the char*-type to void*, i.e. write cout << (void*)data;. Otherwise, when the data type is char*, cout treats data as a '\0'-terminated sequence of characters.

There are, however, other issues: Statement

data = "hamz";

lets data point to a string literal, but it does not copy the string "hamz" into the memory allocated on the heap. You actually loose the pointer to the allocated memory in the heap and produce a memory leak. For copying contents, you'd have to use strcpy(data,"hamz").

Then, as data will point to an (by definition) immutable string literal, data type should be const char*, i.e. const char* myData = "hamz".

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58