0xC0000005:访问冲突写入位置0xCDCDCDCD动态分配错误

问题描述 投票:0回答:1

获取0xC0000005:访问冲突写入位置0xCDCDCDCD,代码如下。我知道我一定没有正确分配指针,但是我不确定在哪里。

我正在尝试让**scoreSet引用*scores的集合,并且需要手动输入*scores。指向数组的names指针工作正常,并且似乎已正确分配。问题是当我尝试为scoreSet模仿相同的内容时,区别在于scoreSet是指向指针数组scores的指针。我觉得我试图动态分配此指针指向的数组的方式是完全错误的。

基本上是在用户输入后试图获得类似的结果: scoreSet0 = {22,33,44} scoreSet1 = {35, 45, 65, 75} scoreSet3 = {10}

#include <iostream>
#include <string>
using namespace std;

int inputData(string*& names, double**& scores);

int main() {
    string *names = nullptr;
    double *scores = nullptr;
    double **scoreSet = &scores;
    int size = 0;
    size = inputData(names, scoreSet);
    for (int i = 0; i < size; i++) {
        cout << *(names+i) << endl;
    }
}

int inputData(string*& names, double**& scoreSet) {
    int numStudents = 0;
    cout << "How many students do you have in the system? ";
    cin >> numStudents;
    while (numStudents <= 0) {
        cout << "Invalid number of students. Please enter number of students: ";
        cin >> numStudents;
    }
    names = new string[numStudents];
    cin.ignore(10000, '\n');
    for (int i = 0; i < numStudents; i++) {
        int numTests = 0;
        cout << "Enter the student's name: ";
        getline(cin,names[i]);
        cout << "Enter how many tests " << *(names + i) << " took: ";
        cin >> numTests;
        *(scoreSet + i)= new double[numTests];                   //Pretty sure this is wrong.
        cin.ignore(10000, '\n');
        for (int j = 0; j < numTests; j++) {                //This loop is causing the error.
            cout << "Enter grade #" << j + 1 << ": ";
            cin >> *(scoreSet+i)[j];
        }
    }
    return numStudents;
}
c++ arrays pointers dynamic-memory-allocation
1个回答
0
投票

根据PaulMcKenzie的建议,这就是它的滚动方式。使用模板可能会有点麻烦,但是如果可以的话...否则,分别创建名称和评分容器。但随后您需要维护重复的代码。

想法是使您的所有物品保持某种顺序。请注意,现在container中负责内存管理。

我放弃了std::cin和分数的处理,但是对于您而言,编写编码时应该没有问题,但要容易得多。那时,不使用std::cin进行开发是浪费时间。您应该编写以便可以编辑和运行。

也要摆脱using namespace std;的习惯,从长远来看会有所收获的。

#define DEV
template<typename T>
struct container {
    size_t size;
    T* ar;
    container(size_t size) :size(size) {
        ar = new T[size];
    }
    ~container() { delete[]ar; }
    T& operator [](size_t pos) { return ar[pos]; }
};
using names_c = container<std::string>;
using scores_c = container<double>;

size_t inputData(names_c& names, scores_c& scores);

int main() {
    container<std::string> names(2);
    container<double> scoreSet(2);

    auto size = inputData(names, scoreSet);
    for (int i = 0; i < size; i++) {
        std::cout << names[i] << endl;
    }
}

size_t inputData(names_c& names, scores_c& scores) {
#ifdef DEV
    size_t numStudents = 2;
    names[0] = "tom";
    names[1] = "mary";
#else
    //do your std::cin stuff
#endif
    return names.size;
}
© www.soinside.com 2019 - 2024. All rights reserved.