从struct vector分配结构指针值

时间:2016-08-29 11:50:18

标签: c++ pointers struct

#include <iostream>
#include <vector>
using namespace std;


struct Sn {
    int SnId;
    double spentEnergy;
};   

class Node {
    //other stuff
    private:
    vector<Sn> SnRecord;

    public:
    int getBestSn(Sn* bestSn);
    void someFunction();

};

int main()
{
   Node nd;
   nd.someFunction();
   return 0;
}
void Node::someFunction() {

    //adding some records in vector just for testing purpose
    Sn temp;
    temp.SnId = 1; temp.spentEnergy = 5;
    SnRecord.push_back(temp);

    temp.SnId = 2; temp.spentEnergy = 10;
    SnRecord.push_back(temp);

    temp.SnId = 2; temp.spentEnergy = 10;
    SnRecord.push_back(temp);
    cout << "Size of SnReocord is " << SnRecord.size() << endl;

    //choosing best sn
    Sn *bestSn;

    int returnCode = -1;
    returnCode = getBestSn(bestSn);
    if (returnCode == 0){ //means there is a best SN
        cout<< "Found best SN with id = "<< bestSn->SnId << endl;
    }
    else {
        cout <<"NO SN "<< endl;
    }
}

int Node::getBestSn(Sn* bestSn) {
    int tblSize = (int)SnRecord.size();
    if (tblSize == 0)
        return -1;
//here i have to assign *bestSn a selected value from vector
//suppose SnRecord[2] is best Sn 

    cout << "Best sn id is " << SnRecord[2].SnId<< endl; //works OK, 
    bestSn = &SnRecord[2]; ///// giving me core dump ERROR in my own program but in this simplified version it only gives wrong value
    return 0;
}

现在的输出是:

 Size of SnReocord is 3                                                                                                                                                                                                     
 Best sn id is 2                                                                                                                                                                                                            
 Found best SN with id = 520004336 

在我自己的程序中,它给了我核心转储错误,如果我对此行进行注释(并根据函数调用进行适当的其他注释),则错误消失并且模拟正常执行。

我看到了数组的例子,如果指针以这种方式分配了值,那就是工作:

int numbers[5];
int * p;
p = &numbers[2]; //works OK.

但对于矢量它不起作用。或者可能是它的结构向量问题,我无法弄清楚。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

好的,实际上问题是通过使用Sn *&amp; amp;的建议来解决的。 bestSn。但我不明白这个解决方案。为什么我不能传递一个指针变量,它会在其中保存一个指针值,后者可以被访问?