gpt4 book ai didi

c++ - 想知道为什么我会遇到段错误

转载 作者:行者123 更新时间:2023-11-28 07:37:02 25 4
gpt4 key购买 nike

我有这段代码,我试图根据用户输入的输入“gen”创建许多数据结构。这是代码:

#include <iostream>
#include <algorithm>
#include <string>
#include <iomanip>
#include <limits>
#include <stdio.h>
#include <sstream>


using namespace std;
using std::stringstream;
struct rootset {
double totSize;
const char *rStrtPtr;
const char *rEndPtr;

struct generations {
double totSize;
const char *genStrtPtr;
const char *genEndPtr;
int numOfGen;
string genName;

struct object {
double objSize;
const char *objStrtPtr;
const char *objEndPtr;
string id;
char markBit;
char objPtr;


struct freeList {
double freeSpace;
int flNumb;
};
};
};
};

int main()
{

int gen =0;
cin >> gen;
cin >> pmemSize;

vector<rootset> pRootSet;
pRootSet.push_back(rootset());
pRootSet[0].totSize = pmemSize;

vector <rootset::generations> generation;
generation.push_back(rootset::generations());

for( i=0; i<gen; i++) {
stringstream out;
out << i;
string s = out.str();
generation[i].genName = "generation" + s
cout<<"gen name: "<<generation[i].genName<<endl;

}
}

这段代码正在打印:

3
50
gen name: generation0
Segmentation fault (core dumped)

但在我的输出中我希望它创建:

gen name: generation0
gen name: generation1
gen name: generation2
gen name: generation3

请让我知道我的代码有什么问题

最佳答案

看起来您正在越界访问 generation。在您进入循环时它的大小为 1,因此该循环仅适用于 gen 等于 0 或 1。

vector <rootset::generations> generation;
generation.push_back(rootset::generations()); // size = 1

for( i=0; i<gen; i++) {
...
generation[i].genName = "generation" + s // what is i?
cout<<"gen name: "<<generation[i].genName<<endl; // what is i?

关于c++ - 想知道为什么我会遇到段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16602209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com