Difference between char *str=”STRING” and char str[] = “STRING”?

The two declarations are not the same.

char ptr[] = "string"; declares a char array of size 7 and initializes it with the characters
s ,t,r,i,n,g and \0. You are allowed to modify the contents of this array.

char *ptr = "string"; declares ptr as a char pointer and initializes it with address of string literal "string" which is read-only. Modifying a string literal is an undefined behavior. What you saw(seg fault) is one manifestation of the undefined behavior.

Leave a Comment