First, a string in C is just a pointer to an array of char that is terminated by the first null character. There is no string concatenation operator in C.
Also, in order to create a new array in C - you need to allocate memory for it using malloc
. However, in the ajout
function, you don't allocate any memory for ch
. Solution:
const size_t len1 = strlen(ch1); //get ch1 length
const size_t len2 = strlen(ch2); //get ch2 length
char *ch = malloc(len1 + len2 + 1); //create ch with size len1+len2+1 (+1
//for null-terminator)
I see you copy each char of ch1
and ch2
into ch
one by one. A better solution would be to copy ch1
and ch2
using memcpy
. Also, after allocation memory using malloc
, you need to deallocate the string using free
:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* ajout(const char *ch1, const char *ch2)
{
//get length of ch1, ch2
const size_t len1 = strlen(ch1);
const size_t len2 = strlen(ch2);
//create new char* array to save the result
char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
//copy ch1, ch2 to result
memcpy(result, ch1, len1);
memcpy(result + len1, ch2, len2 + 1); // +1 to copy the null-terminator
return result;
}
int main()
{
char ch1[] = "hello";
char ch2[] = "ooo";
char *ch = ajout(ch1,ch2);
printf("%s",ch);
free(ch); // deallocate the string
return 0;
}
output:
helloooo
You can read more about memcpy
here and about malloc
here.