What is the difference between char[] s and char * s in C? I understand that both create make 's' a pointer to the array of characters. However,
char s[] = "hello";
s[3] = 'a';
printf("\n%s\n", s);
prints helao
,while
char * s = "hello";
s[3] = 'a';
printf("\n%s\n", s);
gives me a segmentation fault. Why is there such a difference? I'm using gcc on Ubuntu 12.04.
Difference between char s[] and char *s in CThe s[] is an array, but *s is a pointer. For an example, if two declarations are like char s[20], and char *s respectively, then by using sizeof() we will get 20, and 4. The first one will be 20 as it is showing that there are 20 bytes of data.
char* is a pointer to a character, which can be the beginning of a C-string. char* and char[] are used for C-string and a string object is used for C++ springs. char[] is an array of characters that can be used to store a C-string.
In C programming, a string is a sequence of characters terminated with a null character \0 . For example: char c[] = "c string"; When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end by default.
The main difference between them is that the first is an array and the other one is a pointer.
When using char s[] = "hello";
, the char array is created in the scope of the current function, hence the memory is allocated on the stack when entering the function.
When using char *s = "hello";
, s
is a pointer to a constant string which the compiler saves in a block of memory of the program which is blocked for write-access, hence the segmentation fault.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With