I am having trouble concatenating strings in C, without strcat library function. Here is my code
#include
#include
#include<
char a1[] = "Vivek";
Will create a char array a1
of size 6
. You are trying to stuff it with more characters than it can hold.
If you want to be able to accommodate concatenation "Vivek"
and "Ratnavel"
you need to have a char array of size atleast 14 (5 + 8 + 1)
.
In your modified program you are doing:
char *a1=(char*)malloc(100); // 1
a1 = "Vivek"; // 2
1: Will allocate a memory chunk of size 100 bytes, makes a1
point to it.
2: Will make a1
point to the string literal "Vivek"
. This string literal cannot be modified.
To fix this use strcpy to copy the string into the allocated memory:
char *a1=(char*)malloc(100);
strcpy(a1,"Vivek");
Also the for
loop condition i
i
And
a1[i]='\0';
should be
a1[i + len]='\0';
as the new length of a1
is i+len
and you need to have the NUL character at that index.
And don't forget to free
your dynamically allocated memory once you are done using it.