Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...