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 ?
Character literals for C and C++ are char, string, and their Unicode and Raw type. Also, there is a multi-character literal that contains more than one c-char. A single c-char literal has type char and a multi-character literal is conditionally-supported, has type int, and has an implementation-defined value.
char* means a pointer to a character. In C strings are an array of characters terminated by the null character.
An ordinary character literal that contains more than one c-char is a multicharacter literal . A multicharacter literal has type int and implementation-defined value. An integer character constant has type int.
C++ Char is an integral data type, meaning the value is stored as an integer. It occupies a memory size of 1 byte. C++ Char only stores single character.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With