5

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.

PrithviJC
  • 393
  • 3
  • 9

3 Answers3

9

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.

Hetzroni
  • 2,109
  • 1
  • 14
  • 29
5

In both cases, a constant string of characters "hello\0" is allocated in a read-only section of the executable image.

In the case of char* s="hello", the variable s is set to point to the location of that string in memory every time the function is called, so it can be used for read operations (c = s[i]), but not for write operations (s[i] = c).

In the case of char s[]="hello", the array s is allocated on the stack and filled with the contents of that string every time the function is called, so it can be used for read operations (c = s[i]) and for write operations (s[i] = c).

barak manos
  • 29,648
  • 10
  • 62
  • 114
0

One is a pointer the other is an array.

An array defines data that stays in the current scope stack space.

A pointer defines a memory address that is in the current scope stack space, but which references memory from the heap.

Ajk_P
  • 1,874
  • 18
  • 23