简体   繁体   English

如何将单个字符转换为strlen = 1的char *?

[英]How can I convert a single character into a char* with strlen = 1?

I've trying to do this but I can't find the right way. 我正在尝试这样做,但是我找不到正确的方法。 I have this : 我有这个 :

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

int main(){
  char a = 'a';
  char b[1] = " ";
  strcat(b,a);
  printf ("%s",b);
  return 0;
}

I know it's wrong. 我知道是错的 How can I fix this code in order to turn 'a' into "a" ? 我如何解决此代码以便将'a'转换为"a"

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

int main(){
    char a = 'a';
    char b[2] = " ";
    b[0] = a;
    printf ("%s",b);
    return 0;
}

A c string is just an array of characters - if you want to set individual characters in that string, you can do so exactly as you would any other array. c字符串只是一个字符数组-如果要在该字符串中设置单个字符,则可以像设置其他任何数组一样进行设置。

One thing you missed though is that c strings have to be 1 longer than the number of characters you want to store - to store the terminating \\0 . 但是,您错过的一件事是,c字符串必须比要存储的字符数长1-要存储终止\\0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM