I am a student in a CompSci intro class and I have a very basic understanding of pointers in C++. I had noticed in attempting to complete an assignment that a character array / c-string uses pointers differently than other data types.
For example, please consider the following code I created:
#include <iostream>
using std::cout, std::endl;
int main()
{
int inta[] = {1,2,3};
int* p1 = inta;
cout << "p1 = " << p1 << endl;
cout << "*p1 = " << *p1 << endl;
cout << "sizeof(p1) = " << sizeof(p1) <<
", sizeof(*p1) = " << sizeof(*p1) << endl;
char stra[] = "Dog";
char* p2 = stra;
cout << "p2 = " << p2 << endl;
cout << "*p2 = " << *p2 << endl;
cout << "sizeof(p2) = " << sizeof(p2) <<
", sizeof(*p2) = " << sizeof(*p2) << endl;
return 0;
}
The output of *p1 and *p2 are both the first value of the array. However, while the output of p1 is the pointer to the first element of inta (which tracks from online research), the output of p2 is the entire word "Dog". The sizes of p1 and p2 are the same, the size of *p1 and *p2 are 4 and 1 respectively. Is there something I am missing?
I am using Visual Studio Community 2022 and created a normal project.
Thank you, and I appreciate your help!
sizeof(p1)is the size of the pointer, not the pointed-at object.coutdoing the thinking. There is an<<operator overload specifically forconst char *(constbecause it's not going to change the values while printing. That would be dumb) that prints strings because this is what the programmer wants the overwhelmingly vast majority of the time when the have achar *.coutis the output stream, the<<operator modifies the output. I understand now, thank you so much!'D'instra, docout << "p2 = " << (void *)p2 << endlinstead ofcout << "p2 = " << p2 << endl. The effect of the(void *)is producing avoid *pointer fromp2- and that results in a different overload of the stream'soperator<<()(which accepts avoid *) being called - which prints the address passed rather than the contents of the string. To be even more specific (and use a coding style often advocated) usestatic_cast<void *>(p2)instead of(void *)p2