假设我有一个 char
,比如:
char a = 'a';
我怎样才能把它转换成这样的:
char* b = "a";
// b = {'a', '\0'};
(技术上是 2 个 char
,因为它应该以 null 终止)
我的用例是三元表达式,我想将 '\0'
转换为 "\\0"
({ '\\' , '0',\0' }
),但其他每个字符都是一个字母,我希望保持不变。
letter == '\0' ? "\0" : letter;
这有效,但会产生有关类型不匹配的错误。我还有其他可能需要用到的东西。
我尝试过的事情:
letter == '\0' ? "\\0" : letter;
// error: pointer/integer type mismatch in conditional expression [-Werror]
letter == '\0' ? "\\0" : { letter, '\0' };
// ^
// error: expected expression before ‘{’ token
letter == '\0' ? "\\0" : &letter;
// No error, but not null terminated.
letter == '\0' ? "\\0" : (char*) { letter, '\0' };
// ^~~~~~
// error: initialization makes pointer from integer without a cast [-Werror=int-conversion]
//
// ter == '\0' ? "\\0" : (char*) { letter, '\0' };
// ^~~~
// error: excess elements in scalar initializer [-Werror]
// Seems to want to initialise a char* from just the first thing in the list
char string[2] = {letter, 0};
letter == '\0' ? "\\0" : string;
// Makes a string even if it is `'\0'` already. Also requires multiple statements.
char string[2];
letter == '\0' ? "\\0" : (string = {letter, 0});
// ^
// error: expected expression before ‘{’ token
最佳答案
最短
char c = 'a';
char s[2] = {c}; /* Will be 0-terminated implicitly */
puts(s);
打印:
a
如果只是为了能够将字符传递给 puts()
(或类似的),您甚至可以使用复合文字
puts((char[2]){c});
或
{
puts((char[2]){c});
}
后者立即释放复合文字使用的内存。
同时打印
a
还有。
关于将 char 转换为 1 个字符的空终止字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44634528/