concatenate char array in C
Have a look at the strcat function.
In particular, you could try this:
const char* name = "hello";
const char* extension = ".txt";
char* name_with_extension;
name_with_extension = malloc(strlen(name)+1+4); /* make space for the new string (should check the return value ...) */
strcpy(name_with_extension, name); /* copy name into the new var */
strcat(name_with_extension, extension); /* add the extension */
...
free(name_with_extension);
How to concatenate two char arrays in c?
First, you shouldn't return reference to temporary
char con[lena+lenb];
(note that the garbage you get doesn't come from that since you print within the function)
Second, you don't allocate enough memory: should be (with first problem fixed):
char *con = malloc(lena+lenb+1);
then use strcpy/strcat anyway, it's faster, and your original code doesn't do anything useful (mixing chars with array of chars & the size of the arrays isn't known at this moment: that's the reason of the garbage you're getting):
strcpy(con,a);
strcat(con,b);
Or as some suggest that they're unsafe functions, and since we know the size of inputs we can write:
memcpy(con,a,lena);
memcpy(con+lena,b,lenb+1);
Also: the prototype of concat
is really wrong. It should be:
char *concat(const char *a, const char *b){
(as it returns a pointer on chars not a char. And the arguments should be constant pointers so you can use your function with any string)
and you're done (don't forget to free the string when you're done with it)
Fixed code (tested, surprisingly returns hello
, maybe because it compiles without errors with gcc -Wall -Wwrite-strings -Werror
. My advice: turn the warnings on and read them. You'll solve 80% of your problems that way):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *concat(const char *a, const char *b);
int main ()
{
char *con = concat("hel", "lo");
printf("%s\n",con);
return(0);
}
char *concat(const char *a, const char *b){
int lena = strlen(a);
int lenb = strlen(b);
char *con = malloc(lena+lenb+1);
// copy & concat (including string termination)
memcpy(con,a,lena);
memcpy(con+lena,b,lenb+1);
return con;
}
Concatenate char array and char
Rather simple really. The main concern is that tempPrefix
should have enough space for the prefix + original character. Since C strings must be null terminated, your function shouldn't copy more than 28 characters of the prefix. It's 30(the size of the buffer) - 1 (the root label character) -1 (the terminating null character). Fortunately the standard library has the strncpy
:
size_t const buffer_size = sizeof tempPrefix; // Only because tempPrefix is declared an array of characters in scope.
strncpy(tempPrefix, prefix, buffer_size - 3);
tempPrefix[buffer_size - 2] = root->label;
tempPrefix[buffer_size - 1] = '\0';
It's also worthwhile not to hard code the buffer size in the function calls, thus allowing you to increase its size with minimum changes.
If your buffer isn't an exact fit, some more legwork is needed. The approach is pretty much the same as before, but a call to strchr
is required to complete the picture.
size_t const buffer_size = sizeof tempPrefix; // Only because tempPrefix is declared an array of characters in scope.
strncpy(tempPrefix, prefix, buffer_size - 3);
tempPrefix[buffer_size - 2] = tempPrefix[buffer_size - 1] = '\0';
*strchr(tempPrefix, '\0') = root->label;
We again copy no more than 28 characters. But explicitly pad the end with NUL bytes. Now, since strncpy
fills the buffer with NUL bytes up to count
in case the string being copied is shorter, in effect everything after the copied prefix is now \0
. This is why I deference the result of strchr
right away, it is guaranteed to point at a valid character. The first free space to be exact.
Concatenating a char array in C: dynamically handling memory
You are running into undefined behavior since the contents of outputStr
are not initialized properly in the first statement inside the while
loop.
outputStr = realloc(outputStr, 1); // outputStr is not initialized.
Change them to:
outputStr = realloc(outputStr, 2);
strcpy(outputStr, "!");
You are also leaking a whole bunch of memory. The value returned from convertToString
is never free
d.
You can avoid that problem by changing the strategy a little bit.
Change the function to expect a string and use it.
char* convertIntToString(uint8_t integerValue,
char* str)
{
utoa(integerValue, str, 10);
return str;
}
Then, change its usage as:
outputStr = concat(outputStr, convertIntToString(analogValue, str));
You are also leaking memory due to the way you are using concat
.
outputStr = concat(outputStr, ",");
That leaks the old value of outputStr
. You need to keep the old value of outputStr
for a bit longer so you can free
it.
Here's my suggestion for the while
loop:
while (1) {
outputStr = realloc(outputStr, 2);
strcpy(outputStr, "!");
analogValue = ReadADC(0);
char str[4]; // This is the max you need.
// There is no need to malloc and free.
outputStr = concat(outputStr, convertIntToString(analogValue, str));
for(int i = 0; i < 5; i++){
char* newStr = concat(outputStr, ",");
// free the old memory before using the new memory
free(outputStr);
outputStr = newStr;
newStr = concat(outputStr, convertIntToString(analogValue, str));
// free the old memory before using the new memory
free(outputStr);
outputStr = newStr;
}
CDC_Device_SendString(&VirtualSerial_CDC_Interface, outputStr); //send string via USB
free(outputStr);
}
C char array concatenation
Problems with your approach.
C strings must end in 0 byte, in other words
'\0'
character. Using""
adds that automatically, but otherwise you have to add it yourself, and all string functions depend on that 0 being there.Your v array contains characters, not strings, and
strcat
takes strings.
One solution:
char cmd[50] = "some text here";
char *v[] = {"a","s","d","c","b"};
strcat(cmd,v[3]);
This turns your char array into array of pointers to C strings.
Also, it's your responsibility to take care that, cmd[]
contains enough space to hold whatever you add to it with strcat (here it does). It's usually best to use snprintf
to do string concatenation, as it takes total size of the target array including terminating null, and adds that null there always, so it's harder to mess up. Example with your original char array:
char cmd[50] = "some text here";
char buf[50];
char v[] = {'a','s','d','c','b'};
snprintf(buf, sizeof buf, "%s%c", cmd, v[3]);
Notes: sizeof like this works only when buf
really is an array, declared with []
like here. Also with snprintf, using same buffer both as destination and format argument may yield unexpected results, so I added a new destination buffer variable.
One more snprintf example, with your original two arrays only, appending to end of current contents of cmd:
snprintf(cmd + strlen(cmd), (sizeof cmd) - strlen(cmd), "%c", v[3]);
So clearly, in this particular case, the strncat(cmd, &v[3], 1)
suggested in other answers to add 1 character is much nicer, but benefit of snprintf is, you can add all datatype supported by printf, not chars.
How to concat char array into a string
The problem is that you use a very old version of Visual Studio. Much much older than the C++11 standard, which introduced the ability to pass std::string
as filenames to file streams.
You must use a C-style string (const char *
) as filename when opening files with e.g std::ofstream
.
So the solution with your current code is to do
ofstream myfile(concat.c_str());
Concatenate two char* strings in a C program
The way it works is to:
- Malloc memory large enough to hold copies of str1 and str2
- Then it copies str1 into str3
- Then it appends str2 onto the end of str3
- When you're using str3 you'd normally free it
free (str3);
Here's an example for you play with. It's very simple and has no hard-coded lengths. You can try it here: http://ideone.com/d3g1xs
See this post for information about size of char
#include <stdio.h>
#include <memory.h>
int main(int argc, char** argv) {
char* str1;
char* str2;
str1 = "sssss";
str2 = "kkkk";
char * str3 = (char *) malloc(1 + strlen(str1)+ strlen(str2) );
strcpy(str3, str1);
strcat(str3, str2);
printf("%s", str3);
return 0;
}
Related Topics
Sse2 Intrinsics - Comparing Unsigned Integers
Why Can't a Function Go After Main
Converting Steady_Clock::Time_Point to Time_T
What Does It Mean to Return a Reference
_Glibcxx_Use_Cxx11_Abi, Gcc 4.8 and Abi Compatibility
Why Can't I Initialize a Variable-Sized Array
Difference Between Console (/Subsystem:Console) and Windows (/Subsystem:Windows)
Explicit Call to Destructor Is Not Destroying My Object Why
Multiple "Could Not Be Resolved" Problems Using Eclipse with Mingw
Advantage of Using Trailing Return Type in C++11 Functions
Use of 'Auto Func(Int)' Before Deduction of 'Auto' in C++14
How to See the Output of the Visual C++ Preprocessor
Parse String Containing Numbers into Integer Array
Std::Shared_Ptr and Initializer Lists
Observable Behavior and Undefined Behavior -- What Happens If I Don't Call a Destructor