将 char 转换为 1 个字符的空终止字符串

标签 c arrays string pointers char

假设我有一个 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/

相关文章:

计算 parent 向 child 发送信号的次数

c - C中数组冒泡排序和二分查找的组合代码问题

javascript - JavaScript : How to Replace the multiple strings based on conditions

java - 插入排序 - 计算反转次数

c++ - 结构数组成员的默认值

javascript - 如何在文本字段中写入字符串的字符数?

c - c中指向字符串的概念

c - 我怎样才能打破 gdb 中的 UBSan 报告并继续?

c - 为什么json数据包含多余的字符

c - 为什么 C 标准将数据类型的范围定义为一个短?