Strcat concat a char per line?

Using GDB, I find that when I try this operation, I get a segmentation error:

strcat(string,&currentChar); 

Given that the string is initialized as

 char * string = ""; 

and currentChar

 char currentChar = 'B'; 

Why does this lead to a segmentation error?

If strcat cannot be used for this, how else can I concatenate char with a string?

+6
c string char concatenation strcat
source share
6 answers

Since ¤tChar not a string, it does not end with \0 . You must define B as char *currentChar = 'B'; . In addition, according to http://www.cplusplus.com/reference/clibrary/cstring/strcat string should be enough space to store the result string (in this case 2 bytes), but this is only 1 byte.

Or, if you want to use char , then you can do something like (depending on 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"); 
+4
source share

As others react, currentChar is a pointer to char or char * , but a string to C is char [] or const char * .

One way to use strcat to concatenate char string in is to create a minimal string and use it to convert char to string.

Example:

Creating a simple line with 1 character and the suffix '\ 0' ;

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

Application to your question:

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

cToStr will accept the string "B":

 cToStr[0] = currentChar; 

And strcat will work!

 strcat ( string, cToStr ); 
+7
source share

strcat () accepts two lines with \ "0" -terminal. When you pass the address of a character, the procedure will look at the memory that follows the character, looking for a terminator.

Since you do not know what this memory refers to, you should expect problems when your code accesses it.

In addition to this, your string argument does not have a place to add any characters. Where is this memory written? It will try to write to the end of the memory associated with this line.

+1
source share

I think the simplest method (inefficient) would be sprintf

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

0
source share

Both lines must have zero termination. A single char does not terminate zero, so it is undefined when strcat stops concatenating characters to the end. In addition, the row should contain at least enough space for the source row and the resulting row.

It works:

 char string[10] = ""; char* currentChar = "B"; strcat(string, currentChar); 
-one
source share

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

Make the array ample space:

 char buf[1024]; strcat(buf, ""); strcat(buf, "B"); 
-one
source share