矢量指针,C ++

时间:2015-10-30 00:42:38

标签: c++ pointers vector

除最后一行代码外,一切正常。我希望(* v)[0]与aVector [0]相同,即0.0903987。但是这条线无法编译,执行停止工作......任何想法为什么?

var sortField = model.sortField;
var sortReverse = model.sortReverse;
angular.forEach(model.dataCollection, sortField, sortReverse)
  .do(myItem => doSomethingWith(myItem));

输出:

vector<float>* generateNums(int n)
{
    srand(time(NULL));
    RandomNum randomNum(n, seed1, seed2, seed3);
    vector<float> *v = randomNum.getPointer();
    return v;
}


int main()
{
    vector<float> *v = generateNums(ROW_SIZE*COL_SIZE); 

    cout << "v is " << v << endl;
    cout << "(*v)[0] is " << (*v)[0] << endl;   <---this line doesn't work 
}

但如果我摆脱了这个功能,它会编译并得到(* v)[0]的值。

aVector[0] is 0.0903987
&aVector is 0x22fec0
v is 0x22fec0

输出:

int main()
{
    srand(time(NULL));
    RandomNum randomNum(ROW_SIZE*COL_SIZE, seed1, seed2, seed3);
    vector<float> *v = randomNum.getPointer();
    cout << "v is " << v << endl;
    cout << "(*v)[0] is " << (*v)[0] << endl;
}

2 个答案:

答案 0 :(得分:2)

我的预感:

RandomNum randomNum(n, seed1, seed2, seed3);
vector<float> *v = randomNum.getPointer();

上述调用返回指向randomNum成员的指针。函数返回时,randomNum被破坏。因此,返回的值是悬空指针。

一个解决方案

更改函数以返回向量而不是指向向量的指针。

vector<float> generateNums(int n)
{
    srand(time(NULL));
    RandomNum randomNum(n, seed1, seed2, seed3);
    vector<float> v = *(randomNum.getPointer());
    return v;
}

然后,更改用法:

vector<float> v = generateNums(ROW_SIZE*COL_SIZE); 
cout << "v[0] is " << v[0] << endl;

答案 1 :(得分:-1)

generateNums功能,您可以定义名为randomNum本地变量。调用randomNum后,它将被销毁,v将引用您无法访问的已销毁变量。