Reputation: 11
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!
Upvotes: 1
Views: 56
Reputation: 50180
passing a char pointer to an output operator (cout<< or printf etc) will keep reading chars until it reaches the null char at the end of the string
Upvotes: 1