标题
#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
),您正在设置值 *data
到 NULL
。 data
在这里是一个未初始化的指针,因此解引用它是无效的。
你想要的是:
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/