Reputation: 2488
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
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