Difference between char [] and char * in C

What is the difference between char [] s and char * s in C? I understand that both create make 's' a pointer to a character array. Nevertheless,

char s[] = "hello";
s[3] = 'a';
printf("\n%s\n", s);

      

outputs helao

, and

char * s = "hello";
s[3] = 'a';
printf("\n%s\n", s);

      

gives a segmentation fault. Why such difference? I am using gcc on Ubuntu 12.04.

+3


source to share


3 answers


When used, char s[] = "hello";

a char array is created in the scope of the current function, so memory is pushed onto the stack when the function enters.



When used char *s = "hello";

, s

is a pointer to a constant string that the compiler stores in a block of program memory that is locked for write access, hence a segmentation fault.

+7


source


In both cases, a constant character string is "hello\0"

allocated in the read-only section of the executable image.

In the case, the char* s="hello"

variable s

must point to the location of that string in memory each time the function is called, so it can be used for read ( c = s[i]

) operations but not for write ( s[i] = c

) operations .



In the case, the char s[]="hello"

array s

is allocated on the stack and filled with the contents of this string each time the function is called, so it can be used for read ( c = s[i]

) and write ( s[i] = c

) operations .

+4


source


One is a pointer, the other is an array.

The array defines the data that is in the current stack space of the area.

A pointer specifies a memory address that is in the current stack space of the region, but that refers to memory from the heap.

0


source







All Articles