没有输出自己在c中执行strcpy [英] No output for own implementation of strcpy in c
本文介绍了没有输出自己在c中执行strcpy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有些人试图实现自己的strcpy函数,但没有打印输出。请帮忙。
Hi, guys trying to implement own strcpy function, but no output is being printed. Please help.
#include<stdio.h>
#include<string.h>
void strcpy_own(char dest[], char src[], int len);
int main()
{
char src[15]="jeevan", dest[15];
int length=0;
length = strlen(src)+1;
strcpy_own(dest,src,length);
return 0;
}
void strcpy_own(char dest[], char src[], int len)
{
int i=0;
for(i=0;i<len;i++)
{
while(src[i]!='\0')
dest[i]=src[i];
}
dest[strlen(dest)+1]='\0';
printf("%s",dest);
getchar();
}
推荐答案
你的内部而
-loop不会增加i
,
Your innerwhile
-loop does not incrementi
,
for(i=0;i<len;i++)
{
while(src[i]!='\0')
dest[i]=src[i]; // i does not get updated here, the while will never exit
}
将其更改为类似的内容;
Change it to something like this;
for(i=0;i<len;i++)
{
dest[i]=src[i];
if (src[i] =='\0')
break;
}
请记住,您要从<$ c复制最后一个'\0'
$ c> src 到 dest
或 dest
将无法正确终止。
希望这会有所帮助,
Fredrik
Remember that you want to copy the last '\0'
from src
to dest
or dest
won't be properly zero-terminated.
Hope this helps,
Fredrik
我并不感到惊讶。
如果源字符串中的第一个字符不是null,则此循环将永远不会退出:
I'm not surprised.
If the first character in the source string isn't a null, this loop will never exit:
while(src[i]!='\0')
dest[i]=src[i];
试试这个:
Try this:
for(i=0;i<len;i++)
{
dest[i]=src[i];
if (src[i]=='\0') break;
}
请注意循环后的行 - 如果源字符串已满,则可能会超出输出数组。
And be careful with the line after the loop - if the source string is full then you could overrun the output array.
这篇关于没有输出自己在c中执行strcpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文