Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 614
Filip Minx Avatar asked Nov 13 '13 02:11

Filip Minx


People also ask

Can a char be multiple characters in C?

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.

What does char * mean in C?

char* means a pointer to a character. In C strings are an array of characters terminated by the null character.

Can a char have multiple values?

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.

How many characters can be stored in a char * C++?

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.


1 Answers

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.

like image 174
Benjamin Lindley Avatar answered Oct 19 '22 22:10

Benjamin Lindley