Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 十六进制和字符数组打印的区别是什么?_C_Arrays_Char_Printf_Format Specifiers - Fatal编程技术网

C 十六进制和字符数组打印的区别是什么?

C 十六进制和字符数组打印的区别是什么?,c,arrays,char,printf,format-specifiers,C,Arrays,Char,Printf,Format Specifiers,我用c #include <stdio.h> char str[]="hello world"; unsigned char hexvalue[] = {0x01,0x02,0x03,0x04,0x05}; int main() { int i; printf("string %s \n", str); printf("array %x \n", hexvalue); //This line not print whole array why?

我用
c

#include <stdio.h>

char str[]="hello world";
unsigned char hexvalue[] = {0x01,0x02,0x03,0x04,0x05};

int main()
{
    int i;

    printf("string %s \n", str);

    printf("array %x \n", hexvalue); //This line not print whole array why?

    for (i=0;i<sizeof(hexvalue);i++)
    {
        printf ("%x\n",hexvalue[i]);
    }
    return 0;
}
#包括
char str[]=“你好,世界”;
无符号字符hexvalue[]={0x01,0x02,0x03,0x04,0x05};
int main()
{
int i;
printf(“字符串%s\n”,str);
printf(“数组%x\n”,hexvalue);//此行不打印整个数组为什么?

对于(i=0;i,
%x
格式说明符采用无符号int作为输入,并以十六进制打印。它不采用您想要的数组指针

因此,它应该以十六进制打印hexvalue指针的地址,因为它只会将指针视为无符号整数。

  • printf(“字符串%s\n”,str);
工作正常,因为,
%s
需要指向以null结尾的
char
数组的指针,而
str
是(或至少衰减为)一个

  • printf(“数组%x\n”,hexvalue);
不起作用,因为,
%x
需要一个
无符号int
作为参数,而
hexvalue
不是。相反,它会产生

参考:C11标准,§7.21.6.1

如果任何参数不是相应转换规范的正确类型,则行为未定义

另外,请注意,
main()
的建议签名是
int main(void)
printf(“数组%x\n”,hexvalue);

此行不会像您所期望的那样打印整个阵列
它将打印数组的地址
并且数组的地址是数组的第一个索引的地址

%x、 %d否则是将显示在控制台屏幕上的数字类型
在这种情况下,
printf(“数组%x\n”,hexvalue);
它将以十六进制类型打印数组的地址

如果要打印地址,请使用%p

%x
转换说明符将单个
无符号int
作为参数,并将输出格式化为十六进制字符串。它不需要指针值,也不会像
%s
转换说明符那样遍历值数组


循环是打印整个数组内容的唯一方法(尽管对于
unsigned char
类型的值,应使用转换说明符
%hhx
).

在打开警告的情况下编译代码,你就会得到答案。这不是真的。如果参数的类型与格式说明符不匹配,就会出现未定义的行为。现在我绞尽脑汁想弄清楚一个“未定义”的东西实际上是如何“发生的”。@poundifdef:“未定义”简单地说,编译器不需要以任何特定的方式处理这种情况;结果可能是从垃圾输出到崩溃。因此,如果我改为
unsigned char
,改为
unsigned int
,那么它就可以工作了?@Jayesh如果只做这种更改,它绝对不能工作。所以我需要循环打印每个值,然后已经这样做了,那么没有意义接受
unsigned int
@Jayesh您的最佳选择是1)将
hexvalue
更改为
unsigned int
数组,2)去掉
printf(“数组%x\n,hexvalue”);