c - 如何将 "make room"表示为字符串?

标签 c c-strings

我在其他地方发布了这段代码,以了解为什么它没有按预期输出“ratdog”。有人说没有足够的空间将“狗”附加到“老鼠”或其他东西上。他们的意思是什么?

#include <stdio.h>

char *strcat(char*, char*);

char* strcat(char *s, char *t) {
    char* result = *s;
    while(*s != '\0')
        printf("%s", *s);
        *s++;   // advance pointer until you reach the null terminator.

    while(*t != '\0')
        *s = *t;    // copy t to the end of s until we reach the end of t.
    return (char*) result;
}

int main() {
    char rat[] = "rat";
    char dog[] = "dog";
    printf("%s", strcat(rat, dog));
    return 0;
}

最佳答案

您的代码存在 3 个问题:

  1. 复制时将 t 和 s 递增,否则是无限循环。

    while(*t != '\0')
      *s = *t; //See you're only assigning
    
    while(*t != '\0')
      *(s++) = *(t++); //increment them
    

同样,正如 @ihonen 的评论中提到的:*s++;//前进指针直到到达空终止符。 不在循环体内。

  • 为数据源指针指向的数据分配更多的内存,以便它可以包含连接的字符串和\0

      char rat[7] = "rat"; //See i am allocating len(rat) + len(dog) + '\0' = 3+3+1 = 7 
      char dog[] = "dog";
      printf("%s", strcat(rat, dog));
    
  • 第三,您需要在第二个循环之后将 \0 附加到 *s,如下所示 *s = '\0'

  • 关于c - 如何将 "make room"表示为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59593313/

    相关文章:

    字符常量 :\000\xhh

    c - 在 For 循环中 fork() 发生了什么

    dll - VC2019不能使用CString参数(VC6.0内置)

    C++ 缓冲区太小错误

    c - char指针赋值时刻的区别

    c - 将错误写入文件

    c - 可执行加壳程序(解压/解密 stub )

    检查大型 C 项目中常量的#included 位置

    c - c语言将char数组中的数字相加

    c - C 中字符和字符串函数的二维数组