Still seem to be a difference in the way 'char array' and 'int array' are treated. When i execute the program below, printing 'q' will give the address of element 0 of array numbers[0xbf924e4c] as expected. But printing 'p' gives the whole string "Hello"; no address at all.
Both code for int and char are equal, but giving a different result:
- int gives the address
- char gives the stringvalue of the char array
What is this about? And what is the address of letters[]?
Often char pointers/char arrays are used to handle strings (so called C strings) so the operator<< has been overloaded to handle char* differently. This is what makes cout<<"hello" output "hello" and not just some memory address where the string array "hello" happen to be located in memory.
To print the address you can cast the char* into a void*.
Okay static_cast works fine. Thank you for that.
Still, if i copy p (the pointer) to a string, let's say: string getp = p; The string getp doesn't get the address, but will again give the whole string value. As if the value of p intrinsik is NOT the address. Or, does iostream has a catch when copying? I find this very anoying. Maybe you could shed some light on this .
string getp = p; will call the string constructor that takes a const char* as argument. The constructor reads the string content by incrementing the pointer until it finds a null character '\0' that marks the end of the string.
Just to demonstrate how it works, this is how you can loop through each character in letters using char*.
1 2 3 4
for (char* p = letters; *p != '\0'; ++p)
{
cout << *p;
}
This gives me the creeps:
- A char array character and a pointer pntr are defined
- pntr = character;
- to get the address of character i can't use pntr as it gives the value of the string
- I can fall back on &character - but shouldn't it be the same as pntr?
Weird
The pointer points to the first element in the array.
char* p = letters;
is the same as
char* p = &letters[0];
I know it's a bit weird that arrays can be implicit converted to a pointer to the first element just like that but that's just the way it is.
&letters has the same address as p but there is one big difference. The type is different! The type of p is char* (pointer to char) while &letters has type char(*)[6] (pointer to array of 6 characters).
For me it does not explain why there HAS TO BE different output for int versus char:
p = letters: Hello
p = &letters[0]: Hello
*p value at: H
q = numbers: 0xbff2525c
q = &numbers[0]: 1
*q value at: 1
Here is a thread to help you understand , but mostly << is a method that a programmer has written to print a string and not an address , you would need to make a static_cast for char * .