Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C将字符转换为字符串_C - Fatal编程技术网

C将字符转换为字符串

C将字符转换为字符串,c,C,正在尝试将字符转换为C中的字符串: #include <stdio.h> #include <string.h> int main () { int x = 80; char buffer[1] = {0}; buffer[0] = (char) x; printf("%s", buffer); return 0; } #包括 #包括 int main() { int x=80; 字符缓冲区[1]={0}; 缓冲区[0]=(字符

正在尝试将字符转换为C中的字符串:

#include <stdio.h>
#include <string.h>

int main ()
{
    int x = 80;
    char buffer[1] = {0};
    buffer[0] = (char) x;
    printf("%s", buffer);
    return 0;
}
#包括
#包括
int main()
{
int x=80;
字符缓冲区[1]={0};
缓冲区[0]=(字符)x;
printf(“%s”,缓冲区);
返回0;
}
我得了“PP”。 为什么结果是“PP”而不是“P”?调用时

printf("%s", buffer);
您的字符串应该以null结尾。分配缓冲区[0]时,将留下一个1字符长的“字符串”,最后一个字符为“\0”。 尝试:

#包括
#包括
int main()
{
int x=80;
字符缓冲区[2]={0};
缓冲区[0]=(字符)x;
缓冲区[1]='\0';
printf(“%s”,缓冲区);
返回0;
}

您没有足够的空间容纳
'p'
您应该更改此
字符缓冲区[1]={0}
char缓冲区[2]={0}
。注意,您始终需要终止字符串,但在初始化过程中,
字符缓冲区[2]={0}
zero将被强制转换为char,因此char
\0
将被放置在字符串的每个字符中

您的缓冲区太小,只能容纳一个字符-没有空间容纳零终止符,因为这不是一个正确的零终止字符串。@kwl1888请随意,不需要感谢,但如果有帮助,请接受答案。
#include <stdio.h>
#include <string.h>
int main ()
{
    int x = 80;
    char buffer[2] = {0};
    buffer[0] = (char) x;
    buffer[1] = '\0';
    printf("%s", buffer);
    return 0;
}