Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it ok to use a string literal to initialize an unsigned char array but not to initialize an unsigned char pointer?

I have tried compiling with gcc -Wall -pedantic-errors -std=c89 the following code:

int main(){
  unsigned char a[] = "foo";
  unsigned char *b= "foo";
  unsigned char *c= ( unsigned char *) "foo";
  return 0;
}

Why does the second initialization raise the error pointer targets in initialization differ in signedness, but the other two declarations are allowed?

It seems that in the second case, implicit conversion from char *to unsigned char * is not done.

like image 621
jinawee Avatar asked Nov 05 '18 15:11

jinawee


1 Answers

Technically, because the standard explicitly allows arrays of a (any) character type to be initializable with string literals (6.7.9p14):

An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

while for most pointers conversions, the standard requires explicit casts (6.5.4p3):

Conversions that involve pointers, other than where permitted by the constraints of 6.5.16.1, shall be specified by means of an explicit cast.

Intuitively, because you can do:

unsigned char a0 = 'f', a1 = 'o', a2 = 'o';

or in other words, because you can initialize an integer type with a different integer type without having to cast explicitly.

like image 166
PSkocik Avatar answered Sep 21 '22 17:09

PSkocik