我有这个代码,我试图根据用户输入的“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
请告诉我我的代码有什么问题
答案 0 :(得分:1)
看起来您正在访问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?