【发布时间】:2015-10-04 00:06:05
【问题描述】:
我正在尝试使用 strcpy_s,但在处理大小时出现另一个错误,说:L "Buffer is too small && 0" 当我尝试运行程序时,我不知道来自strcpy_s(tochar, sizeof tochar, test.c_str()); 的sizeof tochar 是否正确,因为我不断收到此错误。
完整编译代码:
#include "stdafx.h"
#include <string>
#include <string.h>
#include <cstring>
#include <stdlib.h>
#include <errno.h>
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
#include <iomanip>
#include <stdio.h>
using namespace std;
using std::vector;
using std::string;
int main()
{
std::string test;
std::vector<std::string> v3 = { "filename1", "filename2","filename3", };
for (int m = 0; m < v3.size(); m++) {
test = "\"" + v3[m] + ".txt" + "\"";
char * tochar = new char[test.length() + 1];
strcpy_s(tochar, sizeof tochar, test.c_str());
std::cout << tochar << std::endl;
}
return 0;
}
我不能在 c++ 2015 中使用strcpy,我现在必须使用strcpy_s,因为strcpy 给出了不同的错误,我不想只是关闭错误。 (除非我可以在程序中添加某种代码,让它使用strcpy 编译)
我希望tochar 输出:“filename1.txt”
【问题讨论】:
-
你给 strcpy_s 的第二个参数是错误的。
-
这就是我的想法,所以这就是我发布的原因。
-
这是
tochar缓冲区的长度,而不是指针。您要传递的是缓冲区的分配长度(test.length() + 1)。 -
哦,好吧,因为在 cppreference 的
strcpy_s示例中,它使用了sizeof tochar -
因为在该示例中 tochar 是一个静态数组 (
char tochar[16])。