Difference between char s[] and char *s in C

CServer Side ProgrammingProgramming

We have seen sometimes the strings are made using char s[], or sometimes char *s. So here we will see is there any difference or they are same?

There are some differences. The 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. But second one is showing only 4 as this is the size of one pointer variable. For the array, the total string is stored in the stack section, but for the pointer, the pointer variable is stored into stack section, and content is stored at code section. And the most important difference is that, we cannot edit the pointer type string. So this is read-only. But we can edit array representation of the string.

Example

#include<stdio.h>
main() {
   char s[] = "Hello World";
   s[6] = 'x'; //try to edit letter at position 6
   printf("%s", s);
}

Output

Hello xorld
Here edit is successful. Now let us check for the pointer type string.

Example

#include<stdio.h>
main() {
   char *s = "Hello World";
   s[6] = 'x'; //try to edit letter at position 6
   printf("%s", s);
}

Output

Segmentation Fault
raja
Published on 03-May-2019 07:24:16
Advertisements