Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between char* and char[]

Tags:

c++

I know this is a very basic question. I am confused as to why and how are the following different.

char str[] = "Test"; char *str = "Test"; 
like image 288
Nemo Avatar asked Sep 27 '11 03:09

Nemo


People also ask

What is the difference between char a [] string and char * p string?

char a[]="string"; // a is an array of characters. char *p="string"; // p is a string literal having static allocation. Any attempt to modify contents of p leads to Undefined Behavior since string literals are stored in read-only section of memory.

Is char * the same as char [] in C?

The fundamental difference is that in one char* you are assigning it to a pointer, which is a variable. In char[] you are assigning it to an array which is not a variable.

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.

What is * a [] in C?

char *A[] is an array, and char **A is a pointer. In C, array and pointer are often interchangeable, but there are some differences: 1. with "char *A[]", you can't assign any value to A, but A[x] only; with "char **A", you can assign value to A, and A[x] as well.


2 Answers

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

like image 117
K-ballo Avatar answered Sep 20 '22 21:09

K-ballo


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. 
like image 36
rnrneverdies Avatar answered Sep 20 '22 21:09

rnrneverdies