#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',才能保证复制的完成。