I was just playing with pointers and arrays when I got confused with this piece of code that I was testing with.
#include <iostream>
using namespace std;
int main(void) {
char a[] = "hello";
cout << &a[0] << endl;
char b[] = {'h', 'e', 'l', 'l', 'o', '\0'};
cout << &b[0] << endl;
int c[] = {1, 2, 3};
cout << &c[0] << endl;
return 0;
}
I expected that this would print three addresses(that of a[0], b[0] and c[0]). But the result was:
hello
hello
0x7fff1f4ce780
Why is that for the first two cases with char, '&' gives the whole string or am i missing something here?
In case of a string (character array), the variable itself points to the first element of the array in question. Thus, there is no need to use the '&' operator to pass the address.
Use of Char Array in C Since C Programming Language does not has Data Types. So Char array in C programming is used to store and manipulate the strings.
The ampersand is the address of operator. It returns the memory location of a variable and that's the only way it's used, prefixed to a variable like the engine on a train. The variable doesn't even have to be initialized, just declared.
Used to force string concatenation of two expressions.
Because cout
's operator <<
prints a string if you pass it a char*
as parameter, which is what &a[0]
is. If you want to print the address, you'll have to explicitly cast it to void*
:
cout << static_cast<void*>(&a[0]) << endl;
or just
cout << static_cast<void*>(a) << endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With