[c] How to declare strings in C

Can anyone explain me what is a difference between these lines of code

char *p = "String";
char p2[] = "String";
char p3[7] = "String";

In what case should I use each of the above ?

This question is related to c

The answer is


You shouldn't use the third one because its wrong. "String" takes 7 bytes, not 5.

The first one is a pointer (can be reassigned to a different address), the other two are declared as arrays, and cannot be reassigned to different memory locations (but their content may change, use const to avoid that).


char *p = "String";   means pointer to a string type variable.

char p3[5] = "String"; means you are pre-defining the size of the array to consist of no more than 5 elements. Note that,for strings the null "\0" is also considered as an element.So,this statement would give an error since the number of elements is 7 so it should be:

char p3[7]= "String";

Strings in C are represented as arrays of characters.

char *p = "String";

You are declaring a pointer that points to a string stored some where in your program (modifying this string is undefined behavior) according to the C programming language 2 ed.

char p2[] = "String";

You are declaring an array of char initialized with the string "String" leaving to the compiler the job to count the size of the array.

char p3[5] = "String";

You are declaring an array of size 5 and initializing it with "String". This is an error be cause "String" don't fit in 5 elements.

char p3[7] = "String"; is the correct declaration ('\0' is the terminating character in c strings).

http://c-faq.com/~scs/cclass/notes/sx8.html