我需要创建一个函数来连接2个字符串,在我的情况下它们已经被给出。我需要连接字符串'hello'和'world!'把它变成'helloworld!'。但是,除了strlen()之外,我不能使用库函数。我也需要使用malloc。我知道malloc会创建n个字节的内存,但是,我怎样才能使它返回一个字符串数组,如果可能的话。如何连接使用malloc而不是库函数的2个字符串
这里是我到目前为止,
#include <stdio.h>
#include <string.h>
int *my_strcat(const char* const str1, const char *const str2)
{
int s1, s2, s3, i = 0;
char *a;
s1 = strlen(str1);
s2 = strlen(str2);
s3 = s1 + s2 + 1;
a = char *malloc(size_t s3);
for(i = 0; i < s1; i++)
a[i] = str1[i];
for(i = 0; i < s2; i++)
a[i+s1] = str2[i];
a[i]='\0';
return a;
}
int main(void)
{
printf("%s\n",my_strcat("Hello","world!"));
return 0;
}
由于任何人谁可以帮助我。
返回int *是错误的 –
'strlen()'返回'size_t' * not *'int'。 – alk