Nathan
Nathan

Reputation: 246

Weird output when using char double pointer

I get really weird output from the last cout statement, no idea what would be causing this:

char ex1_val = 'A';
char* ex1;
ex1 = &ex1_val;
cout << *ex1 << endl;
char** ex2;
ex2 = &ex1;
cout << *ex2 << endl;

Here's my output:

A
A����

Upvotes: 0

Views: 239

Answers (3)

rubikonx9
rubikonx9

Reputation: 1413

ex2 is declared as char**, which means it's a pointer to a pointer to char.

When you print the contents of *ex2, you're dereferencing it once, so type of *ex2 is a pointer to char.

Effectively, the compiler assumes, that you want to print a C-style string, which is a NULL-terminated string. So it prints all bytes stored in memory, starting from A stored in ex1_val, followed by random values stored directly after that, until a NULL character is encoutered.

This is actually a very bad situation, as you never know when or if there's a NULL in memory. You might end up trying to access a memory area you're not allowed to use, which may result in crashing the application. This is an example of an undefined behaviour (UB).

To print out the actual contents of ex1_val via the ex2 pointer, you'd need to make it like this:

cout << **ex2 << endl;

where typeof(**ex2) is an actual char.

Upvotes: 3

anukul
anukul

Reputation: 1952

You want to do cout << **ex2 << endl;

ex2, as you have declared it, as a pointer to a pointer to a character. Doing *ex2 only gets you the address of the pointer it is pointing to.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

When you dereference ex2 (in *ex2) you get a pointer to a char (i.e. char*), and the operator<< overload to handle char* outputs it as a C-style zero-terminated string.

Since *ex2 doesn't point to a zero-terminated string, only a single character, you get undefined behavior.

Upvotes: 1

Related Questions