[英]Convert char to 1-character null-terminated string
說我有一個像這樣的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 str[2] = "\0";
str[0] = c;
而且你很好。
或者,當然,如果這是一個經過編碼的值,那么您可以執行以下操作:
char str[2] = "a";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.