[英]my own similar strcat() function prints only one array of chars
I've been trying to practice programming so I decided to try to type the strcat() function myself, or a similar one you know. 我一直在尝试编程,所以我决定尝试自己键入strcat()函数,或者您知道的类似函数。 I typed this code in order to proceed it and I don't know where the problem is. 我键入此代码是为了继续进行操作,但我不知道问题出在哪里。
#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);
}
there are no syntax errors(I hope) the compiler gives me that result: It doesn't concatenate the strings, nothing happens. 没有语法错误(我希望),编译器给我的结果是:它不连接字符串,什么也没发生。
It gives me the same array the same array the user entered, Does anyone has the answer? 它为我提供了与用户输入的数组相同的数组,有人回答吗?
PS: I don't know about the pointers yet. PS:我还不知道这些指针。
Implementing strcat
as a "naive byte-copy loop" is not hard, just do something like this: 将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);
}
Professional libraries will do the copy on "aligned chunk of data" basis, to get a slight performance boost. 专业库将基于“对齐的数据块”进行复制,以略微提高性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.