Filip Minx
Filip Minx

Reputation: 2488

Why can you put multiple characters in C++ char*

I can't figure out how this works.

// This doesn't work (obviously)
char a;
a = "aaa";

// This works
char* a;
a = "aaa";

How come this works ?

Since char type stores only one character or 1 byte number, how can you store more characters in it when you access it through a pointer ?

Upvotes: 7

Views: 13368

Answers (2)

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

You're not putting characters into the char*. You're creating an array of characters in a part of memory determined by your compiler, and pointing the char* at the first character of that array.

The array is actually const, so you shouldn't be able to assign it to a non-const pointer. But due to historical reasons, you still can in many C++ implementations. However, it was officially made illegal in C++11.

Upvotes: 10

kmort
kmort

Reputation: 2928

The second one is a pointer to a string of chars, not a single char. Tutorial.

Upvotes: 2

Related Questions