您的位置:首页 > 其它

c strcpy strncpy

2016-07-04 16:29 246 查看
          strcpy把从src地址开始且含有'\0'结束符的字符串复制到以dest开始的地址空间,返回值的类型为char*.

   strncpy 拷贝数据,不包含最后的null-terminated.

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
const char* p = "hello world";
char des[128];
//memset(des, 0x00, sizeof(des));
/*
Warning: If there is no null byte among the first n bytes of src, the string placed in dest will  not  be
null-terminated.
*/
strncpy(des, p, 7);//不包含最后的null-terminated.
cout << des << endl;//打印出乱码
return 0;
}


#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <string.h>

int main()
{
char *src = "123 hello world";
char des[6] = { 0, };
//strncpy(des, src, strlen(src));//奔溃
strncpy(des, src, sizeof(des) - 1);//最多拷贝des的长度-1,最后一个放置 '\0'
printf("%s\n",des);
}

//讨论优先级 * 和++ 是同一优先级但是,后加加时执行完语句后执行++操作


//讨论优先级 * 和++ 是同一优先级但是,后加加时执行完语句后执行++操作
char* strcpy(char* des,const char* source)
{
 
 char* r=des;
   
  assert((des != NULL) && (source != NULL));
 
 while((*r++ = *source++)!='\0');
 
 return des;
 
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: