strcat的Concat的一个char到一个字符串? [英] strcat concat a char onto a string?

查看:192
本文介绍了strcat的Concat的一个char到一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用GDB我发现我得到一个段错误,当我尝试此操作:

Using GDB i find I get a segfault when I attempt this operation:

strcat(string,&currentChar);

由于字符串作为

char * string = "";

和currentChar是

and currentChar is

char currentChar = 'B';

为什么这导致段错误?
如果strcat的不能用于此,还能怎么我Concat的一个char到一个字符串?

Why does this result in a segfault? If strcat can't be used for this, how else can I concat a char onto a string?

推荐答案

由于&放大器; currentChar 是不是一个字符串,它不会与 \\ 0 字符。你应该定义 B 的char * currentChar ='B'; 。此外,根据 http://www.cplusplus.com/reference/clibrary/cstring/strcat 字符串应该有足够的空间来容纳结果字符串(2字节在这种情况下),但也仅仅是1个字节。

Because &currentChar is not a string, it doesn't finish with \0 character. You should define B as char *currentChar = 'B';. Also according to http://www.cplusplus.com/reference/clibrary/cstring/strcat string should have enough space to hold the result string (2 bytes in this case), but it is only 1 byte.

或者,如果你想使用字符那么你可以做一些事情(取决于您的code的),如:

Or if you want to use char then you can do something like (depending of your code):

char string[256];
...

char currentChar = 'B';
size_t cur_len = strlen(string);
if(cur_len < 254) {
    string[cur_len] = currentChar;
    string[cur_len+1] = '\0';
}
else
    printf("Not enough space");

这篇关于strcat的Concat的一个char到一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆