0

我一直在尝试练习编程,所以我决定尝试自己键入 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:我还不知道指针。

4

1 回答 1

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

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

于 2017-11-24T14:22:55.220 回答