Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcat concat a char onto a string?

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?

like image 703
Blackbinary Avatar asked Jan 29 '11 02:01

Blackbinary


1 Answers

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 );
like image 61
gagallo7 Avatar answered Sep 24 '22 07:09

gagallo7