I’m working in C, and I have to concatenate a few things.
Right now I have this:
message = strcat('TEXT ', var); message2 = strcat(strcat('TEXT ', foo), strcat(' TEXT ', bar));
Now if you have experience in C I’m sure you realize that this gives you a segmentation fault when you try to run it. So how do I work around that?
In C, ‘strings’ are just plain
chararrays. Therefore, you can’t directly concatenate them with other ‘strings’.You can use the
strcatfunction, which appends the string pointed to bysrcto the end of the string pointed to bydest:Here is an example from cplusplus.com:
For the first parameter, you need to provide the destination buffer itself. The destination buffer must be a char array buffer. E.g.:
char buffer[1024];Make sure that the first parameter has enough space to store what you’re trying to copy into it. If available to you, it is safer to use functions like:
strcpy_sandstrcat_swhere you explicitly have to specify the size of the destination buffer.Note: A string literal cannot be used as a buffer, since it is a constant. Thus, you always have to allocate a char array for the buffer.
The return value of
strcatcan simply be ignored, it merely returns the same pointer as was passed in as the first argument. It is there for convenience, and allows you to chain the calls into one line of code:So your problem could be solved as follows: