strcat concat a char onto a string?

我是研究僧i 提交于 2019-12-18 03:33:53

问题


Using GDB, I find I get a segmentation fault when I attempt this operation:

strcat(string,&currentChar);

Given that string is initialized as

char * string = "";

and currentChar is

char currentChar = 'B';

Why does this result in a segmentation fault?

If strcat can't be used for this, how else can I concat a char onto a string?


回答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.

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");



回答2:


As responded by others, &currentChar is a pointer to char or char*, but a string in C is char[] or const char*.

One way to use strcat to concatenate a char to string is creating a minimum string and use it to transform a char into string.

Example:

Making a simple string, with only 1 character and the suffix '\0';

char cToStr[2];
cToStr[1] = '\0';

Applying to your question:

char * string = "";
char currentChar = 'B';

cToStr will assume the string "B":

cToStr[0] = currentChar;

And strcat will work!

strcat ( string, cToStr );



回答3:


strcat() takes two '\0'-terminated strings. When you pass the address of a character, the routine will look at the memory that follows the character, looking for the terminator.

Since you don't know what that memory even refers to, you should expect problems when your code accesses it.

In addition to that, your string argument does not have room to have any characters appended to it. Where is that memory written to? It will attempt to write past the end of the memory associated with this string.




回答4:


I think the simplest method (not efficient) would be sprintf

sprintf(str, "%s%c", str, chr);




回答5:


Both of the strings must be null-terminated. A single char isn't null terminated, so it's undefined when strcat will stop concatenating characters to the end. Also, string must contain at least enough space for both the original string and resultant string.

This works:

char string[10] = "";
char* currentChar = "B";
strcat(string, currentChar);



回答6:


The first argument of strcat must have enough space to hold the rest of the string. "" is a constant string and as such GCC does not allocate space.

Make it an array with enough space:

char buf[1024];

strcat(buf, "");
strcat(buf, "B");


来源:https://stackoverflow.com/questions/4834811/strcat-concat-a-char-onto-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!