我没有弄错。我试图得到一个指针,使用另一个的地址来获取在开始时创建的对象。
class Soldier{
public:
Soldier(char c){
type = c;
}
char type;
};
//a 2d vector of armies and its soldiers
vector< vector<Soldier> > *armys = new vector< vector<Soldier> >(3, vector<Soldier>(5, Soldier('@')));
//making a pointer array
Soldier **deployment = new Soldier*[3*5];
//test if it works:
//show the original value
cout << "the third soldier of the first army is of type " << (*armys)[1][2].type << endl;
//initializing the pointers of the deployment array to make them point to the Object through the vector.
(*deployment)[1 * (armys->size()) + 2] = (*armys)[1][2];
//show the value via the pointer
cout << "the third soldier of the first army is of type " << (*deployment)[1 * (armys->size()) + 2].type << endl;
上面的代码在显示第二条消息之前触发了分段错误。
答案 0 :(得分:1)
在以下语句中,将Soldier
对象复制到单位指针的位置。这只会出错:
(*deployment)[1 * (armys->size()) + 2] = (*armys)[1][2];
deployment
是一个3 * 5指针的一维数组。所以你必须首先初始化数组元素中的指针(而不是复制对象):
deployment[1 * (armys->size()) + 2] = &(*armys)[1][2]; // take address of armys element
然后你可以通过指针间接引用你的Soldier
对象:
cout << "the third soldier of the first army is of type "
<< deployment[1 * (armys->size()) + 2]->type << endl;
请注意,对于Soldier **deployment
,deployment[i]
将是指向Soldier
的指针。
虽然更正后的代码有效,但在1D数组中计算索引的方式可能会在以后给您带来麻烦,因为它不准确。假设你想带上你最后一支军队的最后一名士兵(*armys)[2][4]
。在您的方案中,您将使用deployment[2 * armys->size()+4]
。但是armys->size()
是3,所以你要取元素deployment[10]
而不是14.在你的索引“flatening”中你应该取每行的大小而不是行数。假设每支军队的大小始终相同,那么deployment[i * (*armys)[0].size()+j]
(*armys)[i][j]
初始化循环因此可以是:
for (int i=0; i<armys->size(); i++)
for (int j=0; j<(*armys)[i].size(); j++)
deployment[i * (*armys)[0].size()+j] = &(*armys)[i][j];
顺便说一下,当索引从0开始时,(*armys)[1][2]
将成为文本输出中第二个军队(不是第一个)的第3个士兵。