strcpy() 使用失败

 
  
#include < stdio.h >
#include
< string .h >
#include
< stdlib.h >
#define NL 100

int main()
{
char s0[NL], s1[NL];
memset(s0,
0 , sizeof (s0));
memset(s1,
0 , sizeof (s1));
s0[
1 ] = 1 ;
strcpy(s1, s0);
return 0 ;
}

 

拷贝的结果是:s1 = "",s1[1] = 0;

分析:strcpy()函数的功能是字符串拷贝,而字符串是以/0为结束标志。所以简单的把strcpy()当成数组的拷贝是错误的想法。

参考:

strcpy


function
<cstring>
char * strcpy ( char * destination, const char * source );

Copy string

Copies the C string pointed by source into the array pointed by destination, including the terminating null character.

 

To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.

 

Parameters

destination
Pointer to the destination array where the content is to be copied.
source
C string to be copied.

 

 

Return Value

destination is returned.

 

 

Example

 
   
/* strcpy example */
#include
< stdio.h >
#include
< string .h >



int main ()
{
  char str1[] = " Sample string " ;
  char str2[ 40 ];
  char str3[ 40 ];
  strcpy (str2,str1);
  strcpy (str3,
" copy successful " );
  printf (
" str1: %s\nstr2: %s\nstr3: %s\n " ,str1,str2,str3);
  return 0 ;
}

 

 

Output:


str1: Sample string
str2: Sample string
str3: copy successful

转载于:https://www.cnblogs.com/superbin/archive/2010/07/31/1789158.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值