1

I am new to c++ and I have a question about the array of pointers. In the following program

#include <iostream>

using namespace std;

int main(){
    char b[10];
    char* a[10]; 
    b[0] = 'b';
    a[0] = &b[0];
    cout << a[0] << endl;
    return 0;

}

a is an array of pointers pointing to char objects. a[0] is then assigned the address of b[0], but why the cout result is a c-string b rather than the its address ? I thought a[0] should be storing a pointer. Thank you very much in advance.

XXX
  • 69
  • 1
  • 5

3 Answers3

2

The expression a[0] has a type of char *.

The << operator, when give a value of char *, interprets it as a '\0' terminated text string, and that's what you see. That's how it works.

Just by the luck of the draw, the second char of b, b[1], turned out to be a binary zero, which serves perfectly as a '\0', however this is undefined behavior, and is technically a bug (a.k.a. a nasal demon).

Sam Varshavchik
  • 98,597
  • 5
  • 74
  • 125
2

std::cout reads c-string and print that when char* is passed.

a[0] is char* and pointer is stored there.

Therefore, the data b in the array b is read and printed.

To have std::cout print addresses, cast the addresses to void* like cout << (void*)a[0] << endl;.

Also note that what is in the array b is not c-string because it is not null-terminated. b[1] = '\0'; should be added before cout << a[0] << endl;.

MikeCAT
  • 69,090
  • 10
  • 44
  • 65
2

but why the cout result is a c-string b rather than the its address ?

Because pointers to characters are handled differently than all other pointer types are handled by character streams: They are required to be pointers to null terminated string, and content of that string will be printed. In other words, the behaviour is as if %s format specifier was used with printf.

This is in order to make following program work as one might expect:

const char* str = "Hello, World!";
std::cout << str; // expected output is Hello, World!
                  // expected output is not an address

In your program the array a is not guaranteed to be null terminated because you didn't initialise any element to be the null character. As such, the pre-condition is not necessarily satisfied in which case the behaviour of the program is undefined.

I thought a[0] should be storing a pointer.

a[0] is a pointer.

eerorika
  • 223,800
  • 12
  • 181
  • 301