I have to make a function which concatenates two strings but I have to add a ‘\n’ after the first word. I figured everything out and for some reason it doesn’t print out anything. Any ideas? It probably has to do something with the pointers. I just can’t get my head around them. Here’s the code.
char *function(char *s1, char *s2){
char *newStr;
int size;
size = strlen(s1) + strlen(s2);
newStr = (char *)malloc((size+1)*sizeof(char));
while(*s1!= '\0'){
*newStr = *s1;
newStr++;
s1++;
}
*newStr = '\n';
newStr++;
while(*s2 != '\0'){
*newStr = *s2;
newStr++;
s2++;
}
*newStr = '\0';
return newStr;
}
int main (int argc, const char * argv[]) {
char *str1 = "Hello";
char *str2 = "World";
printf("%s",function(str1, str2));
return 0;
}
So as a result I should get:
Hello
World
but I’m not getting anything back.
You are returning a pointer to the end of the buffer rather than a pointer to the start of the buffer. Look at the last two lines of the function:
Clearly this returns a pointer to the null
char, i.e. the empty string.Solve the problem by introducing a temporary pointer which you will use to step through the output buffer. Then you can return the pointer to the beginning of the output buffer.
You also need to allocate an extra char for the
\n, as shown above. Finally, your calling code never frees the memory allocated byfunction.