我需要創建一個函數來連接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