Why can not I declare and set a char-pointer variable to point to a char array?

advertisements

What's wrong with the initialization of s2 in the code below?

#include <stdio.h>

int main()
{
  char *s1 = "foo";
  char *s2 = {'f', 'o', 'o', '\0'};

  printf("%c\n", s1[1]);
  printf("%c\n", s2[1]);
  return 0;
}

I thought because I could initialize s1 the way I did above, the initialization of s2 should work fine as well.

But this code leads to compile-time warnings as well as run-time segmentation fault.

$ gcc foo.c
foo.c: In function ‘main’:
foo.c:6: warning: initialization makes pointer from integer without a cast
foo.c:6: warning: excess elements in scalar initializer
foo.c:6: warning: (near initialization for ‘s2’)
foo.c:6: warning: excess elements in scalar initializer
foo.c:6: warning: (near initialization for ‘s2’)
foo.c:6: warning: excess elements in scalar initializer
foo.c:6: warning: (near initialization for ‘s2’)
$ ./a.out
o
Segmentation fault (core dumped)


A better question to ask is why you can initialize a pointer with a string literal, because inability to initialize a pointer using an array initializer should come as no surprise: after all, arrays are not pointers.

String literals, however, are special. C lets you use them to initialize both arrays and pointers in order to provide a convenient syntax for creating null-terminated strings. That is why your first syntax works with both an array of characters and a character pointer.