strncpy(s,t,n)将t中最多前n个字符复制到s中

ljf913 2011-09-26 10:56:48
#include <stdio.h>

char *strncpy(char *s, char *t, int n);

void main()
{
char s[100], t[100];
int n;
scanf("%s %d",t,n);
printf("%s\n",strncpy(s,t,n));
}
/* strncpy(s,t,n)将t中最多前n个字符复制到s中,并返回s。如果t中少于n个字符,则用'\0'填充*/

char *strncpy(char *s, char *t, int n)
{
int i;
char *p;
p = s;
for (i = 1; i <= n; i++)
{
*s++ = *t++;
}
for (; i <= n; i++)
{
*s++ = '\0';
}
return p;
}

编译、连接都没有错误,但是一运行windows就停止。请各位帮忙看一下哪里错了?
...全文
432 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2011-09-26
  • 打赏
  • 举报
回复
C:\Program Files\Microsoft Visual Studio 10.0\VC\crt\src\strncpy.c
/***
*strncpy.c - copy at most n characters of string
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
* defines strncpy() - copy at most n characters of string
*
*******************************************************************************/

#include <cruntime.h>
#include <string.h>

/***
*char *strncpy(dest, source, count) - copy at most n characters
*
*Purpose:
* Copies count characters from the source string to the
* destination. If count is less than the length of source,
* NO NULL CHARACTER is put onto the end of the copied string.
* If count is greater than the length of sources, dest is padded
* with null characters to length count.
*
*
*Entry:
* char *dest - pointer to destination
* char *source - source string for copy
* unsigned count - max number of characters to copy
*
*Exit:
* returns dest
*
*Exceptions:
*
*******************************************************************************/

char * __cdecl strncpy (
char * dest,
const char * source,
size_t count
)
{
char *start = dest;

while (count && (*dest++ = *source++)) /* copy string */
count--;

if (count) /* pad out with zeroes */
while (--count)
*dest++ = '\0';

return(start);
}
赵4老师 2011-09-26
  • 打赏
  • 举报
回复
VC调试(TC或BC用TD调试)时按Alt+8、Alt+6和Alt+5,打开汇编窗口、内存窗口和寄存器窗口看每句C对应的汇编、单步执行并观察相应内存和寄存器变化,这样过一遍不就啥都明白了吗。
(Linux或Unix下可以在用GDB调试时,看每句C对应的汇编并单步执行观察相应内存和寄存器变化。)
想要从本质上理解C指针,必须学习汇编以及C和汇编的对应关系。
从汇编的角度理解和学习C语言的指针,原本看似复杂的东西就会变得非常简单!
指针即地址。“地址又是啥?”“只能从汇编语言和计算机组成原理的角度去解释了。”

提醒:
“学习用汇编语言写程序”

“VC调试(TC或BC用TD调试)时按Alt+8、Alt+6和Alt+5,打开汇编窗口、内存窗口和寄存器窗口看每句C对应的汇编、单步执行并观察相应内存和寄存器变化,这样过一遍不就啥都明白了吗。
(Linux或Unix下可以在用GDB调试时,看每句C对应的汇编并单步执行观察相应内存和寄存器变化。)
想要从本质上理解C指针,必须学习C和汇编的对应关系。”
不是一回事!
火头军 2011-09-26
  • 打赏
  • 举报
回复
n改成&n
char *strncpy(char *s, char *t, int n)

中第二个for 是不会执行的 以为第一个for循环完i就大于n了
所以你的没有结束符
bdmh 2011-09-26
  • 打赏
  • 举报
回复
n改成&n
还有,你能确保你的s有结束符吗,假如s被填充满,好像你没有设置结束符
就想叫yoko 2011-09-26
  • 打赏
  • 举报
回复
scanf("%s %d",t,n);
改为
scanf("%s %d",t,&n);
吧, 至少

70,023

社区成员

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

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