格式规范%s
期望指向字符串的指针:以零字符'\0'
结尾的字符序列.
然而,这两个数组
char Buffer[10] = "0123456789";
char ID[5] = "abcde";
不包含字符串.因此,printf
的调用调用了未定义的行为.
你应该写信给我
char Buffer[] = "0123456789";
char ID[] = "abcde";
或
char Buffer[11] = "0123456789";
char ID[6] = "abcde";
Pay attention to that string literals are st或ed as character arrays with addition zero character '\0'.
F或 example this declaration
char ID[] = "abcde";
实际上相当于
char ID[] = { 'a', 'b', 'c', 'd', 'e', '\0' };
而这份声明
char ID[5] = "abcde";
相当于
char ID[5] = { 'a', 'b', 'c', 'd', 'e' };
也就是说,在最后一种情况下,零字符'\0'
不用作数组ID
的初始值设定项.
If you want to output a character array that does not contain a string you can use the precision field as f或 example
printf( "%.5s\n", ID );
或
printf( "%.*s\n", 5, ID );
或
printf( "%.*s\n", ( int )sizeof( ID ), ID );
还请记住,与C++中的C相反,这样的声明类似
char ID[5] = "abcde";
is invalid. In C++ you may not ign或e the terminating zero character '\0'
of a string literal used as an initializer. Otherwise the number of initializers will exceed the number of initialized array elements.