How do I print the data stored in the char*
array [In C, we use %p
to display addresses].
char * tokens[5];
for(int i=0;i<5;i++)
tokens[i] = new char[5];
for(int i=0;i<5;i++)
std::cout<<"Address: "<<tokens[i]<<std::endl;
/*Add data in the array*/
for(int i=0;i<5;i++)
delete[] tokens[i];
This gives me,
Address:
Address:
Address:
Address:
Address:
I understand that must be because, tokens[i]
is the start address of a string so cout
prints the string which as of now is empty.
What do I have to typecast tokens[i]
to at std::cout
?
operator<<
is overloaded for char*
and it assumes you have a null-terminated character array that you want printed. Cast it to a void*
to get the value of the pointer instead:
std::cout << "Address: " << static_cast<void*>(tokens[i]) << std::endl;
See running code here: https://ideone.com/9Cst8F