关于strcpy函数的溢出问题
以下是我的程序,当我把arr2[15]改成arr2[14]时会打印空行#include <stdio.h>
#include <string.h>
//字符串拷贝函数string copy :strcpy(destination,source);
// 内存设置函数memory set :memset(point,value,num);
int main()
{
char arr1[]="Hello,Remained";//内涵Hello/0 :/0是结束符所以覆盖后没显示yWorld,直接终止了打印
char arr2[15]="ByeBey World!";
printf("定义arr1:%s\n",arr1);
printf("定义arr2:%s\n",arr2);
strcpy(arr2,arr1);//strcpy(被覆盖对象,覆盖所用资源)把arr1的字符串放arr2里了
printf("将arr1覆盖arr2后显示arr2:%s\n",arr2);//显示:Hello,Remained
//如果arr1 比arr2的字符串数多,就不能显示arr1了,因为溢出了
printf("arr1覆盖arr2后显示arr1:%s\n",arr1);//显示:*****,Remained
memset(arr1,'*',5); //指向的字符串对象,需要配置的内容,数量
printf("将5个*配置给arr1后,打印arr1:%s\n",arr1);//显示:*****,Remained
return 0;
}
arr1[14]时编译效果如下:
定义arr1:Hello,Remained
定义arr2:ByeBey World!
将arr1覆盖arr2后显示arr2:Hello,Remained
arr1覆盖arr2后显示arr1:
将5个*配置给arr1后,打印arr1:*****,Remained
--------------------------------
Process exited after 0.0373 seconds with return value 0
请按任意键继续. . .
arr[15]时编译效果如下:
定义arr1:Hello,Remained
定义arr2:ByeBey World!
将arr1覆盖arr2后显示arr2:Hello,Remained
arr1覆盖arr2后显示arr1:Hello,Remained
将5个*配置给arr1后,打印arr1:*****,Remained
--------------------------------
Process exited after 0.03908 seconds with return value 0
请按任意键继续. . .