Okay, so I'm trying to pass a pointer to a argument like this.
void function(vector<vector<int> > *i){
vector<int> j;
j.push_开发者_高级运维back(5);
i->push_back(j);
}
And call it with function(&i)
But when I do it says i[0][0] is 0 and not 5.
Why is this happening?
Edit:
int main(){
vector<vector<int> > test;
function(&test);
cout << test[0][0];
}
You can try this code:
void f(vector<vector<int> > *i)
{
vector<int> j;
j.push_back(5);
i->push_back(j);
}
vector<vector<int> > i;
f(&i);
cout << i[0][0];
Output:
5
Demo: http://ideone.com/hzCtV
Or alternatively, you can also pass by reference as illustrated here : http://ideone.com/wA2tc
I assume you are calling your function as function(test)
and not function(&test)
as the second one will not compile. Your code in main
is wrong. You should declare test as vector<vector<int> > test;
(without *
). At its current form, you have just defined pointer to a vector without actually allocating the vector itself. If you try to dereference this pointer (you are trying to do i->push_back()
you will invoke undefined behavior.
At least on my machine, this gives me 5!
#include <vector>
#include <stdio.h>
using std::vector;
void vf(vector<vector<int> > * i) {
vector<int> j;
j.push_back(5);
i->push_back(j);
}
int main() {
vector<vector<int> > j;
vf(&j);
printf("c: %d\n",j[0][0]);
}
You should use references instead of pointers unless NULL is an acceptable value for the pointer. By doing this you can avoid having to test for a NULL pointer condition and it helps clean up the syntax.
精彩评论