【问题标题】:I want to convert a string to a char using strcpy_s, but it gives a size error我想使用 strcpy_s 将字符串转换为字符,但它给出了大小错误
【发布时间】: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])。

标签: c++ string strcpy


【解决方案1】:

到 strcpy_s 的第二个副本应该是您希望复制的字符数。

strcpy_s(tochar, test.length() + 1, test.c_str());

我认为这是一种写法。

sizeof tochar

给你的是 char 指针变量的大小,而不是你分配的数组的大小。

【讨论】:

    【解决方案2】:

    而不是这个 strcpy_s(tochar, sizeof tochar, test.c_str());你需要做 strcpy_s(tochar, test.length() + 1, test.c_str());

    当您说 sizeof tochar 时,您的值是 4 或 8,因为它是一个指针。 但是对于api,你需要告诉目标数组的大小

    【讨论】:

      【解决方案3】:

      使用 strcpy 尽量不要使用

      #include <stdio.h>
      

      使用

      #include <cstdio>
      

      【讨论】:

      • 这不能回答问题,不推荐使用strcpy,因为它可能会导致缓冲区溢出,因此不安全。
      • @Aracthor 不会将错误答案标记为低质量。
      猜你喜欢
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 2019-12-31
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多