如何使用malloc而不是库函数连接2个字符串

时间:2016-10-22 02:48:31

标签: c string-concatenation

我需要创建一个连接2个字符串的函数,在我的例子中,它们已经给出了。我需要连接字符串' hello'和世界!'进入' helloworld!'。但是,除了strlen()之外,我不能使用库函数。我还需要使用malloc。我知道malloc会为内存创建n个字节,但是,如果可能的话,我如何才能使它返回一个字符串数组。

这是我到目前为止所拥有的,

#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;
}

感谢任何可以帮助我的人。

3 个答案:

答案 0 :(得分:3)

这是一个替代修复。首先,您忘记了#include <stdlib.h> malloc()。您从函数char返回指向my_strcat()的指针,因此您需要更改函数原型以反映这一点。我还更改了const声明,以便指针不是const,只有它们指向的值:

char * my_strcat(const char *str1, const char *str2);

您对malloc()的电话投放错误,并且有no reason to do so anyway in C。您还试图将malloc()中的参数转换为size_t。您可以这样做,但必须用括号括起类型标识符:

a = malloc((size_t) s3);

相反,我已将s1, s2, s3, i的类型声明更改为size_t,因为所有这些变量都用于字符串长度和数组索引的上下文中。

循环是最重要的变化,也是我在函数原型中更改const的原因。你的循环看起来很好,但你也可以使用指针。通过递增指针,递增计数器i来逐步执行字符串,并将存储在那里的值存储在i的{​​{1}}位置。最后,索引a已经增加,以指示一个超过最后一个字符的位置,并存储一个&#39; \ 0&#39;那里。请注意,在原始代码中,计数器i未递增以指示连接字符串的空终止符的位置,因为您在循环i时重置它。 @jpw显示了解决此问题的一种方法。

我稍微改变了str2。我声明了一个指向main()的指针,以便从函数调用中接收返回值。这样,当你完成它时,你可以char分配内存。

以下是修改后的代码:

free()

答案 1 :(得分:2)

使用指针来解决这个问题更简单:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *mystrcat(char *a, char *b) {
  char *p, *q, *rtn;
  rtn = q = malloc(strlen(a) + strlen(b) + 1);
  for (p = a; (*q = *p) != '\0'; ++p, ++q) {}
  for (p = b; (*q = *p) != '\0'; ++p, ++q) {}
  return rtn;
}

int main(void) {
  char *rtn = mystrcat("Hello ", "world!");
  printf("Returned: %s\n", rtn);
  free(rtn);
  return 0;
}

但你可以用索引做同样的事情:

char *mystrcat(char *a, char *b) {
  char *rtn = malloc(strlen(a) + strlen(b) + 1);
  int p, q = 0;
  for (p = 0; (rtn[q] = a[p]) != '\0'; ++p, ++q) {}
  for (p = 0; (rtn[q] = b[p]) != '\0'; ++p, ++q) {}
  return rtn;
}

答案 2 :(得分:0)

有一些问题:

malloc的回复中你不需要进行任何演员表演(无论如何你都有错误演员的语法)(更多信息见this)。

您需要为malloc函数包含标题stdlib.h

最重要的是,a[i]='\0';中的i不是您需要的;你想在末尾添加null char,它应该是a[s3]='\0';(s1 + s2的长度)。

这个版本应该是正确的(除非我遗漏了一些东西):

#include <stdio.h>
#include <stdlib.h> //for malloc
#include <string.h>

char *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 = malloc(s3);
    for(i = 0; i < s1; i++) {
        a[i] = str1[i];
    }
    for(i = 0; i < s2; i++) {
        a[i+s1] = str2[i];
    }
    a[s3-1] = '\0'; // you need the size of s1 + s2 + 1 here, but - 1 as it is 0-indexed

    return a;
}


int main(void)
{
    printf("%s\n",my_strcat("Hello","world!"));
    return 0;    
}

使用Ideone进行测试会显示此输出:Helloworld!