为什么可以使用字符串文字来初始化无符号字符数组,但不能初始化无符号字符指针? [英] Why is it ok to use a string literal to initialize an unsigned char array but not to initialize an unsigned char pointer?

查看:34
本文介绍了为什么可以使用字符串文字来初始化无符号字符数组,但不能初始化无符号字符指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 gcc -Wall -pedantic-errors -std=c89 编译以下代码:

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?

似乎在第二种情况下,从 char *unsigned char * 的隐式转换没有完成.

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

推荐答案

从技术上讲,因为标准明确允许(任何)字符类型的数组可以用字符串字面量(6.7.9p14):

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

字符类型的数组可以用字符串初始化文字或 UTF-8 字符串文字,可选用大括号括起来.字符串文字的连续字节(包括终止的 null字符(如果有空间或数组大小未知)初始化数组的元素.

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.

虽然对于大多数指针转换,标准要求显式转换(6.5.4p3):

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

涉及指针的转换,除非在允许的情况下6.5.16.1 的约束,应通过方式指定一个明确的演员.

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.

直觉上,因为你可以:

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.

这篇关于为什么可以使用字符串文字来初始化无符号字符数组,但不能初始化无符号字符指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆