Summary: In this tutorial, we will learn what is the difference between char and char* in the C/C++ programming languages.
We as programmers often use
char* to store and access multiple characters under the same name. While they work the same in most cases, they differ from each other in a lot of ways.
Here is the table that summarizes the difference between
char* in C/C++:
char allocates an array to store the characters values, whereas the
char* assigns a pointer to the variable.
Though both allows to store and access the successive characters of the string literal (including the null character ‘
\0‘), they allocate the values into different types of memory.
char puts the literal string in read-only memory and copies its content to the stack memory, allowing us to modify its values.
char name = "Pencil Programmer"; name = 'X'; //OK
char* puts the string literal in the static read-only memory and returns a pointer referring to it. Thus, trying to modify its values causes an error.
char* name = "Pencil Programmer"; name = 'X'; //Not OK
char is a structure that references a certain section of the memory (which starts with the address of the first character of the string literal), allowing things like indexing which makes accessing values very fast.
char* is the pointer variable that holds the address of the first character of the string literal.
Beneath the surface, char* uses pointer arithmetic to access the characters of the string literal.
char will always start from the same memory address, but using the arithmetic operators on
char* pointer variable, we can change the address to which it points.
char* name = "programming"; name = name+3; cout << name; //outputs 'gramming'
And the last major difference between
char* is that the
char gets destroyed when the control goes out of the containing scope, whereas the memory allocated to
char* remains for the lifetime of the program.