Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ ampersand operator with char arrays

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?

like image 340
scarecrow Avatar asked Jun 12 '13 17:06

scarecrow


People also ask

Why is ampersand not used in array?

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.

Can we use char in array in C?

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.

How does ampersand work in C?

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.

What is the use of ampersand operator?

Used to force string concatenation of two expressions.


1 Answers

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;
like image 185
Luchian Grigore Avatar answered Sep 25 '22 05:09

Luchian Grigore