【问题标题】:my own similar strcat() function prints only one array of chars我自己的类似 strcat() 函数只打印一个字符数组
【发布时间】:2017-11-24 13:46:44
【问题描述】:

我一直在尝试练习编程,所以我决定尝试自己键入 strcat() 函数,或者您知道的类似函数。我输入了这段代码以继续它,但我不知道问题出在哪里。

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


void main(){

  int i, j;
  char a[100]; char b[100];
    printf("enter the first string\n");
    scanf("%s", &a);
    printf("enter the second string\n");
    scanf("%s", &b);

    for(i =0; i<100; i++){
      if(a[i] == '\0')
      break;
    }


  //  printf("%d", i);

   for(j = i; j<100; j++){
      a[j+1] = b[j-i];
      if(b[j-i] == '\0')
      break;
  }

    printf("%s", a);

}

没有语法错误(我希望) 编译器给了我这个结果:它没有连接字符串,什么也没有发生。

它给了我与用户输入相同的数组相同的数组,有人有答案吗?

PS:我还不知道指针。

【问题讨论】:

  • 你能在这里添加你的代码吗?
  • edit您的问题并在那里发布您的代码。而不是代码图片,发布代码。
  • 请在此处以文本形式发布您的代码,包括任何错误和输出。它使这里的人们更容易调试它并保留它的记录以防人们将来遇到类似的问题
  • scanf("%s",a)
  • 第二个循环以j=i 开始。 a 中的 NUL。但是您将b 的值分配给a[j+1],因此第一个更改的字符是a[i+1]。因此,NUL 保持在原来的位置,并且在打印 a 时看不到效果

标签: c arrays string.h


【解决方案1】:

strcat 实现为“简单的字节复制循环”并不难,只需执行以下操作:

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

char* strdog (char* restrict s1, const char* restrict s2)
{
  s1 += strlen(s1); // point at s1 null terminator and write from there
  do
  {
    *s1 = *s2; // copy characters including s2's null terminator
    s1++;
  } while(*s2++ != '\0'); 

  return s1;
}

int main(void)
{
  char dst[100] = "hello ";
  char src[] = "world";

  strdog(dst, src);
  puts(dst);
}

专业库将在“对齐的数据块”的基础上进行复制,以获得轻微的性能提升。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    相关资源
    最近更新 更多