Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

string

pointers

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.

like image 515
PrithviJC Avatar asked Sep 12 '14 19:09

PrithviJC


People also ask

What is difference between char [] and char * in C?

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.

What does char * [] mean in C?

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.

What does char [] do in C?

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.

What's the difference between a char *) and a char * *?

The main difference between them is that the first is an array and the other one is a pointer.


1 Answers

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.

like image 167
Hetzroni Avatar answered Oct 19 '22 21:10

Hetzroni