c++ - 段错误并返回存储在元素中的值?

标签 c++

标题

#ifndef INTVECTOR_H
#define INTVECTOR_H

using namespace std;
class IntVector{
private:
    unsigned sz;
    unsigned cap;
    int *data;
public:
    IntVector();
    IntVector(unsigned size);
    IntVector(unsigned size, int value);
    unsigned size() const;
    unsigned capacity() const;
    bool empty() const;
    const int & at (unsigned index) const;
};

#endif

主要

#include "IntVector.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> iVector;
int *array;
IntVector::IntVector(){
    sz = 0;
    cap = 0;
    *data = NULL;
    vector<int> iVector (sz);
    iVector.reserve(sz);
}

IntVector::IntVector(unsigned size){
    sz = size;
    iVector.resize(sz);
    iVector.reserve(sz);
    cap = iVector.capacity();
    array = new int[sz];
    array = 0;
}

IntVector::IntVector(unsigned size, int value){
    sz = size;
    iVector.reserve(sz);
    cap = iVector.capacity();
    array = new int[sz];
    for(int i = 0; i < sz; i++){
        array[i] = value;
    }
}

unsigned IntVector::size() const{
    return sz;
}

unsigned IntVector::capacity() const{
    return cap;
}

bool IntVector::empty() const{
    if(sz > 0){
        return false;
    }
    else{
        return true;
    }
}

const int &IntVector::at(unsigned index) const{
    if(index > sz){
        exit(0);
    }
    else{
        return array[index];
    }
}

当我遇到段错误时,我遇到了一个试图将 int *data 设置为 NULL 的讨厌问题。我应该使用什么方法将 *data 分配给 IntVector 中的 Null 以避免段错误?看起来我没有将任何内容重新分配给 *Data,所以我有点困惑。

我问题的第二部分是 IntVector::at 函数。它应该返回存储在传入索引位置的元素中的值,但我不确定如何直接返回该值,因为它是一个动态分配的数组,而且我在谷歌上读到的内容非常困惑。我是否必须使用特殊参数来访问该值?谢谢。

最佳答案

*data = NULL;

您没有将 data 设置为 NULL(更喜欢 nullptr),您正在设置 *dataNULLdata 在这里是一个未初始化的指针,因此解引用它是无效的。

你想要的是:

data = NULL;

或者,更好

data = nullptr;

或者,最好使用初始化列表。

IntVector::IntVector() : sz(0), cap(0), data(nullptr)
{
    // I removed your vector initialization since 
    // you're just using sz, which has a value of 0.
    // iVector is already initialized here, but I don't
    // believe that you mean to shadow it as you are doing.
    // iVector is declared statically, and then again here.
}

关于c++ - 段错误并返回存储在元素中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21893041/

相关文章:

c++ - 是否可以将 Boost uint128_t 数据类型存储到原始 int 中?

C++ setenv 解析其他变量

c++ - SDL2 OpenGL 窗口立即关闭

c++ - 如何在 C++ 中初始化动态数组?

c++ - 为什么在没有返回类型的情况下显式调用构造函数时会返回一个临时对象?

c++ - 特征行 vector 超出范围会产生 “Run-Time Check Failure #2 - Stack around the variable X was corrupted”

c++ - 代理模式可以容纳模板函数吗?

c++ - 无法将char数组写入Windows注册表项

c++ - 双线性插值伪影

c++ - 从 Maya C++ API 中的变换节点获取网格节点