C++strcpy和strcpy_s,解决:C4996This function or variablemay be unsafe;strcpy_s函数不接受两个参数

一.解决:C4996不符合函数“strcpy”规范;This function or variablemay be unsafe;

代码:

#include <iostream>
#include <cstring>
using namespace std;
int main() {
	char b[4];
	char a[4] = "abc";
	strcpy(b, a);
	cout << b << endl;

错误:
在这里插入图片描述
解决方案:

#define _CRT_SECURE_NO_WARNINGS

代码:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
int main() {
	char b[4];
	char a[4] = "abc";
	strcpy(b, a);
	cout << b << endl;
}

结果:
在这里插入图片描述

二.strcpy_s函数

strcpy_s(b,strlen(a)+1, a);//此处+1,因为char结尾多出一个'\0';

代码:

#include <iostream>
#include <cstring>
using namespace std;
int main() {
	char *b;
	char a[4] = "abc";
	b = (char*)malloc(strlen(a) + 1);
	strcpy_s(b,strlen(a)+1, a);
	cout << b << endl;
}

结果:
在这里插入图片描述


版权声明:本文为weixin_44190648原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。