将char转换为1个字符的以null结尾的字符串

时间:2017-06-19 15:31:38

标签: c arrays string pointers char

说我有char喜欢:

char a = 'a';

如何将其转换为以下内容:

char* b = "a";
// b = {'a', '\0'};

(技术上2 char s,因为它应该为空终止)

我的用例是三元表达式,我想将'\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

2 个答案:

答案 0 :(得分:5)

最短的

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

答案 1 :(得分:0)

char str[2] = "\0";
str[0] = c;

你很高兴。

当然,如果这是一个带编码的值,那么你可以这样做:

char str[2] = "a";
相关问题