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[] and 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[] and char* in C/C++:

char[]char*
char[] allocates an array.char* allocates a pointer.
char[] allocates values in the stack memory and the values after assignment can be modified (e.g. charArray[i] = 'x')char* allocates values on the static read-only memory, hence the values cannot be modified.
char[] is structured, so it allows indexing.char* doesn’t allow indexing.
The char[] lives as long as the containing scope.char* lives for the entire life of the program

The 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.

The 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[2] = 'X';    //OK

Whereas the 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[2] = 'X';     //Not OK

The 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.

Whereas the 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.

The 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[] and 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.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply