使用strcpy时C 访问违规读取地点

C++ Access violation reading location when using strcpy

本文关键字:读取 访问 strcpy 使用      更新时间:2023-10-16

在Ubuntu终端中编译的命令是g++ scrap.c -std=c++11

我查看了其他错误的问题,但没有一个使用strcat,这是我发生异常的地方。

我试图将所有字符从test1复制到一次512个字符中的temp[]中,但是我得到了一个例外Access violation reading location 0x...

我要做的另一件事是将温度加载到fileArray[]的项目中,但是代码底部的strcpy是给我no suitable conversion from str to "char *" exists

我努力给出一个"完整,最小,可验证的例子",因为管理员似乎现在真的很难推动这一点。请让我知道我是否在这里做。您应该能够复制我的代码并使用G 进行编译以检查它。

scrap.c(更新(:

//#include <stdafx.h>
//#include "stdafx.h"
#include <stdio.h>  /* defines FILENAME_MAX */
#include <assert.h>
#include <iostream>
#include <fstream>
#include <cstring>
//#include <filesystem>
#include <experimental/filesystem>
#include "dirent.h"
//#include <direct.h>
using namespace std;

int main() {
    string test1 = "This is test1.txt...This is test1.txt...";
    std::vector<std::string> fileArray[10];
    string temp = "";
    for (int a = 0; a < 10; a++) {
        int block = 512 * a;
        int currentBlockPosition = 0;
        while (currentBlockPosition < 512 && (currentBlockPosition + block) < test1.size()) {
                    temp += test1.at(block + currentBlockPosition);
                    cout << "block + currentBlockPos: " << block + currentBlockPosition << endl;
                    cout << "current char: " << test1.at(block + currentBlockPosition) << endl;
                    currentBlockPosition++;
            }
            temp = "";
            cout << "temp: " << temp << endl;
            cout << "a: " << a << endl;
            //fileArray[a] =  temp; // no operator "=" matches these operands    ... operand types are: std::vector<std::string, std::allocator<std::string>> = std::string
    }
}

找到了解决方案。

使用char []而不是string,访问违规错误与我有关。

使用fileArray->push_back(temp);证明是正确的语法而不是fileArray[a] = temp

另外,我必须在while()中添加第二个条件,以避免界限错误。