I am trying to learn C programming, and I am doing an exercise that
I need write a function that accepts two strings. Use the malloc() function to allocate enough memory to hold the two strings after they have been concatenated (linked). Return a pointer to this new string.
For example, if I pass "Hello " and "World!", the function returns a pointer to "Hello World!".
and I wrote the following code,
Code:
#include <stdio.h>
#include <stdlib.h>
#define LEN 20
//const short int LEN = 20;
char *stringConcat(char s1[], char s2[]);
int main(void)
{
char str1[LEN], str2[LEN];
char *ptrString;
printf("Enter a value string 1:");
scanf("%20s", str1);
printf("Enter a value string 2:");
scanf("%20s", str2);
ptrString = stringConcat(str1, str2);
printf("The two string are now concated, it becomes\n%s\n\n",ptrString);
return 0;
}
char *stringConcat(char s1[], char s2[])
{
int i1 = 0, i2=0,i=0;
//local pointer;
char *ptr1=NULL;
while(s1[i1]!='\0')
i1++;
while(s2[i2]!='\0')
i2++;
ptr1 = (char *) malloc(i1+i2+1 * sizeof(char));
for (i=0; i<i1; i++)
{
ptr1++ = s1[i]; //the problem must be here
}
for (i=0; i<i2; i++)
{
ptr1++ = s2[i]; ////the problem must be here
}
printf("%s", ptr1); // you would see sth unreadable
return ptr1; // the returned values would be unreadable Ascii codes
}