c++ - 声明 int 变量时出现分段错误(核心转储)错误
问题描述
我试图创建类向量。这是我的代码
#include <bits/stdc++.h>
using namespace std;
template<class t>
class vec{
t *start;
int size=0;
public:
void add_value(t a){
*(start+(sizeof(t)*size)) = a;
cout << (start+(sizeof(t)*size))<< " = "<< *(start+(sizeof(t)*size))<<endl;
size++;
// cout << start<< endl;
}
void operator [](int i){
cout << (start+(sizeof(t)*i))<< " = "<< *(start+(sizeof(t)*i))<<endl;
}
int length(){
return size;
}
};
int main(){
vec<int> t;
cout << t.length()<<endl;
t.add_value(8);
t.add_value(10);
cout << t.length()<<endl;
t[1];
}
这给了我正确的输出。
0
0x7fff0fe9b5d0 = 8
0x7fff0fe9b5e0 = 10
2
0x7fff0fe9b5e0 = 10
但是当在 main 函数中声明一个 int 变量时。
int main(){
int i=0; //newline
vec<int> t;
cout << t.length()<<endl;
t.add_value(8);
t.add_value(10);
cout << t.length()<<endl;
t[1];
}
输出。
0
Segmentation fault (core dumped)
我还尝试了打印起始变量和新 int 变量 int 的地址,它们是不同的。
解决方案
你可能想要这样的东西:
#include <iostream>
using namespace std;
template<class t>
class vec {
t* start = new t[100]; // initialize the pointer (fixed size of 100, to be improved)
int size = 0;
public:
void add_value(t a) {
*(start + size) = a;
size++;
}
t operator [](int i) { // should return a t instead of a void
return *(start + i);
}
int length() {
return size;
}
};
int main() {
vec<int> t;
cout << "t.length() = " << t.length() << endl;
t.add_value(8);
t.add_value(10);
cout << "t.length() = " << t.length() << endl;
// display all values in t
for (int i = 0; i < t.length(); i++)
{
cout << "t[" << i << "] = " << t[i] << endl;
}
}
所有乘法sizeof(t)
都已被删除,因为指针算术已经为您完成了这项工作。
这个非常简陋且极简的示例可以按您的预期工作,但是您可以在类中存储的最大元素数为 100。我将改进留给您作为练习。
顺便说一句,您还需要做许多其他改进,尤其是您需要一个析构函数,并且可能需要三法则
笔记:
*(start + x)
您应该替换所有start[x]
执行完全相同的操作但更惯用且更具可读性的实例。
推荐阅读
- batch-file - INNO 设置 - CMD .bat 问题(PrivilegesRequired=admin,在代码部分,直接在 cmd 中工作)
- xamarin.ios - 使用 xamarin.ios c# 以编程方式添加嵌套的堆栈视图
- ios - Firebase 规则:无法始终如一地工作
- javascript - 前端动态表的最佳实践
- xcode - Swift 4 NSUnknownKeyException 错误
- c - “jmp”的操作数类型不匹配
- laravel - Laravel Slack 通知的奇怪问题
- python - 使用 pip install 时出现错误“找不到满足要求 PIL 的版本”
- vb.net - 修剪特定的字符串
- c - 不兼容的指针类型警告重新指向 int 指针数组的指针