c++中的strncpy

#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;



int main()
{
	char sentence1[]="Hello world Hi world Hello world Hi world";
	char sentence2[20]="Hi world";
	char buffer[10];
	cout<<sentence1<<endl;
	cout<<sentence2<<endl;

	strncpy(buffer,sentence1,9);
	buffer[9]='\0';

	cout<<"After copy: "<<endl;
	cout<<"sentence1: "<<sentence1<<endl;
	cout<<"sentence2: "<<sentence2<<endl;
	cout<<"buffer: "<<buffer<<endl;

	return 0;
}



定义一个buffer数组,用strncpy时limit只能为数组大小减一,留一个出来作为结束'\0',才能保证复制的完成。


阅读更多
文章标签: c++ buffer
个人分类: C++基础
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭