Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 '';

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...