有没有一种方法可以通过以下方式使用'printf'打印字符数组(我知道这不是正确的C代码,我想知道是否有替代方法可以产生相同的结果)。
printf("%s", {'h', 'e', 'l', 'l', 'o' });
这将起作用,但是必须将数组的长度硬编码为格式字符串或作为参数,否则必须将数组定义两次(也许通过一个宏),以便编译器可以计算其大小:
printf("%.5s", (char []) {'h', 'e', 'l', 'l', 'o' });
How about a simple while loop? Assuming the array is null-terminated, of course. If not - you'll need to adjust to counting the number of characters in the array.
char a[] = {'h','e','l','l','o','\0'};
int i = 0;
while (a[i] != "\0")
{
printf ("%c,", a[i]);
i++;
}
Output:
h,e,l,l,o,
Note: do NOT try this on a char**
! This is for char[]
only!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.