在不更改输入的情况下实现strcat

时间:2018-09-22 16:11:45

标签: c strcat

我想创建C strcat函数的实现以连接2个字符串,而不修改任何一个输入字符串。这是我到目前为止所拥有的

char *my_strcat(char* s1, char* s2)
{
  char* p = malloc(strlen(s1) + strlen(s2) + 1);
  while (*s1 != '\0')
    *p++ = *s1++;
  while (*s2 != '\0')
    *p++ = *s2++;
  *p++ = '\0';
  return p;
}

我想用s1和s2中的所有字符填充p,但是此代码什么也不返回。可以使用一些帮助。

4 个答案:

答案 0 :(得分:3)

由于要在串联过程中增加p

*p++ = *s1++; 

*p++ = '\0'; //don't do p++ here

p将在连接后指向超出其分配的内存。

只需添加一个指向p开头的伪指针并返回它即可。

请在下面找到示例代码。

char *my_strcat(const char* s1,const char* s2)
{
  char *p = malloc(strlen(s1) + strlen(s2) + 1);

  char *start = p;
  if (p != NULL)
  {
       while (*s1 != '\0')
       *p++ = *s1++;
       while (*s2 != '\0')
       *p++ = *s2++;
      *p = '\0';
 }

  return start;
}

答案 1 :(得分:3)

  

我想用s1和s2中的所有字符填充p,但是此代码什么也不返回。可以使用一些帮助。

您先从一个malloc指针开始,然后逐渐增加p

在例程结束时,您希望该p指向什么?

使用这种方法,您需要记住已分配的指针并返回该指针。

您可能会发现,如果给变量赋予更有意义的名称-至少在开始时-可以对其进行更好的推理。

此外,由于您没有修改输入,因此应将它们标记为const。这样可以更好地传达您的意图-并在编译时检查您实际要完成的工作。如果您要重用诸如strcat之类的名称,并且具有预期的期望,那么这一点尤其重要。 (重命名是您可能会重新考虑的另一件事。)

char *my_strcat(const char* s1, const char* s2)
{
  char* result = malloc(strlen(s1) + strlen(s2) + 1);

  // To satisfy @P__J__ I will expand on this by saying that
  // Your interface should document what the behavior is when
  // malloc fails and `result` is NULL.  Depending on the
  // overall needs of your program, this might mean returning
  // NULL from my_strcat itself, terminating the program, etc.
  // Read up on memory management in other questions.

  char* dest = result;
  while (*s1 != '\0')
     *dest++ = *s1++;
  while (*s2 != '\0')
      *dest++ = *s2++;
  *dest++ = '\0';
  return result;
}

答案 2 :(得分:2)

您正在移动指针*p本身,因此即使复制了数据,它(指针p)也已经放在前面,所以要做的是使另一个指向内存的指针这样做:

char *my_strcat(char* s1, char* s2)
{
     char* p = malloc(strlen(s1) + strlen(s2) + 1);
     char *c=p;    //RATHER THAN POINTER P, POINTER C WILL TRAVEL/MOVE
     while (*s1 != '\0')
          *(c++) = *(s1++);
     printf("%s\n\n",p);
     while (*s2 != '\0')
          *(c++) = *(s2++);
     *c = '\0';
     return p;
}

因此,在这种情况下,指针p仍保留在其原始位置,指向内存空间的开始。

答案 3 :(得分:-1)

另一个答案。这次没有没有明确的临时char指针来保存原始指针。并且const正确的类型+ malloc检查。

友好得多的编译器优化器:)

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


static inline char *strcpys(char *dest, const char *src)
{
    while(*dest++ = *src++);
    return dest;
}

char *mystrcat(const char *str1, const char *str2)
{
    char *result = malloc(strlen(str1) + strlen(str2) + 1);

    if(result)
    {
        strcpys(strcpys(result, str1) - 1, str2);
    }
    return result;
}

int main()
{
    char *str1 = "12345";
    char *str2 = "ABCDE";
    char *dest;

    printf("%s + %s = %s\n", str1, str2, (dest = mystrcat(str1, str2)) ? dest : "malloc error");

    free(dest);
    return 0;
}
相关问题