Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer to array c++

Tags:

c++

My understanding about assigning an array to a pointer is that the pointer is pointing at the first index of the array, so when printout the pointer, it should print out the address of the first index of the array, but how come in this case the cout printed out the value of the whole array? even though I explicitly indicated that I wanted the address of the first index

char foo[] = {'A','B','C','\0'};
char* p = foo;
char* q = &(foo[0]);
cout <<"from p:  " << p << endl;
cout << "from q: " <<  q << " " << &(foo[0]) <<  endl;

//output
from p:  ABC
from q: ABC ABC

the second question is that I see the difference between those two lines is that one is an array of pointer to char, the other is a pointer to a char array, is that correct? is the parenthesis necessary?

 char* bar1[4];
 char (*bar2)[4] = &foo;
 cout << "address of foo is  " << bar2  << endl;
 //output
 address of foo is  0x7fff192f88b0

The address of the foo array should be the same as the address of A, right? How do I printout the address of A? since I failed to do so. Thank you very much

like image 374
Cong Hui Avatar asked Jul 28 '26 14:07

Cong Hui


1 Answers

<< has a dedicated overload for const char *, because that's what a C-style string is. Try this:

cout << static_cast<const void *>(bar2) << endl;
like image 126
Oliver Charlesworth Avatar answered Jul 30 '26 04:07

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!