c++ – Difference between char* and char[]

c++ – Difference between char* and char[]

char str[] = Test;

Is an array of chars, initialized with the contents from Test, while

char *str = Test;

is a pointer to the literal (const) string Test.

The main difference between them is that the first is an array and the other one is a pointer. The array owns its contents, which happen to be a copy of Test, while the pointer simply refers to the contents of the string (which in this case is immutable).

The diference is the STACK memory used.

For example when programming for microcontrollers where very little memory for the stack is allocated, makes a big difference.

char a[] = string; // the compiler puts {s,t,r,i,n,g, 0} onto STACK 

char *a = string; // the compiler puts just the pointer onto STACK 
                    // and {s,t,r,i,n,g,0} in static memory area.

c++ – Difference between char* and char[]

A pointer can be re-pointed to something else:

char foo[] = foo;
char bar[] = bar;

char *str = foo;  // str points to f
str = bar;        // Now str points to b
++str;            // Now str points to a

The last example of incrementing the pointer shows that you can easily iterate over the contents of a string, one element at a time.

Leave a Reply

Your email address will not be published.