Reputation: 15
I wrote a function to concatenate two strings (s
= "computer"
; t
= "keyboard"
), but my code only returns "keyboard"
. Please point out the mistakes.
char *concat(char *s, char *t) {
s = malloc((strlen(s) + strlen(t) + 1) * sizeof(char));
char *p = s;
while (*p != '\0') {
++p;
}
while (*t != '\0') {
*p++ = *t++;
}
*p = '\0';
return s;
}
I do not want to use strcat()
. This is a test program from Stepik, so I cannot change anything in the main
function.
Here is the question: Write a function which receives two character pointers and returns a new character pointer representing their concatenation.
Upvotes: 1
Views: 2195
Reputation: 144770
You are on the right track:
Yet there are some issues:
malloc()
,const char *
as you do not modify these strings.Here is a corrected version:
#include <stdlib.h>
#include <string.h>
char *concat(const char *s, const char *t) {
char *ret = malloc((strlen(s) + strlen(t) + 1) * sizeof(char));
char *p = ret;
while (*s != '\0') {
*p++ = *s++;
}
while (*t != '\0') {
*p++ = *t++;
}
*p = '\0';
return ret;
}
Upvotes: 0
Reputation: 67546
char *myconcat(const char *s1, const char *s2)
{
size_t len1,len2;
char *result = malloc((len1 = strlen(s1)) + (len2 = strlen(s2)) + 1);
if(result)
{
memcpy(result, s1, len1);
memcpy(result + len1, s2, len2 + 1);
}
return result;
}
Upvotes: 2
Reputation: 448
You have s="computer" when passed into a function, and then on the very first line you reassign it with malloc, so "computer" is gone. You can debug your program step by step, or just print the values to the console. This will help you to find the error.
Upvotes: 0