编写strcpy(s,t,n)函数 ,将t中最多前n个字符复制到s中

newlangwen1 2011-08-18 09:16:53
#include <stdio.h>
void strcpy(char *s,char *t,int n);
main()
{
char t[]="hello";
char s[]="";
strcpy(s,t,2);
printf("result:%s",s);
system("pause");
}

void strcpy(char *s,char *t,int n)
{
int count;
count =0;
while((*s++ =*t++)&&(count <n))
count++;
}
执行的结果是:hello 为什么呢 count 的限制不起作用 怎么把t中元素都复制到s中了,哪里出了问题 ,请大家帮助解答一下
...全文
274 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
CJacky++ 2011-08-19
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 newlangwen1 的回复:]
问题找到了,char s[]="";数组没设置大小,但是我不是很理解,为什么不设置大小,t中字符全复制去了呢
[/Quote]
你确定结果是“hello”,不是“helllo”?
ljhhh0123 2011-08-19
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 cmarquis 的回复:]

你确定结果是“hello”,不是“helllo”?
[/Quote]
++++++
CJacky++ 2011-08-18
  • 打赏
  • 举报
回复
两个问题:
1. char s[]="";
这个句子只给s数组分配一个字节的空间,所以数组越界是肯定的,结果是不可预期的。
2. strcpy没有在复制完后加结束符,当是count >= n造成循环退出的,s字串是不带结束符时,不宜使用printf输出结果。


#include <stdio.h>
void strcpy(char *s,char *t,int n);
int main()
{
char t[]="hello";
char s[10]={0};
strcpy(s,t,2);
printf("result:%s\n",s);
system("pause");
}

void strcpy(char *s,char *t,int n)
{
int count;
count =0;
while((*s++ =*t++)&&(count <n))
count++;
*s = '\0';
}



newlangwen1 2011-08-18
  • 打赏
  • 举报
回复
问题找到了,char s[]="";数组没设置大小,但是我不是很理解,为什么不设置大小,t中字符全复制去了呢
ljhhh0123 2011-08-18
  • 打赏
  • 举报
回复
楼主能把函数名写得和标准库函数不一样吗?
#include <stdio.h>
void mystrcpy(char *s,char *t,int n);

char t[]="hello";
char s[6];
main()
{

mystrcpy(s,t,2);
printf("result:%s",s);
system("pause");
}

void mystrcpy(char *s,char *t,int n)
{
int count;
count =0;
while ((*s++ =*t++)&&(count <n))
count++;
}
kanyeming 2011-08-18
  • 打赏
  • 举报
回复
复制完加个0封口
至善者善之敌 2011-08-18
  • 打赏
  • 举报
回复
不是都复制了,只是复制了3个字符而已while((*s++ =*t++)&&(count <n))
这里循环了2遍,第三遍又执行了一次*s++ =*t++,但count <n条件不满足退出了
quwei197874 2011-08-18
  • 打赏
  • 举报
回复
循环完了才加,当然不行了

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧