CyanPrime
CyanPrime

Reputation: 5193

Passing a vector<vector<int> > pointer to a argument?

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];
}

Upvotes: 1

Views: 5565

Answers (4)

jbruni
jbruni

Reputation: 1247

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.

Upvotes: 0

fnokke
fnokke

Reputation: 1161

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]);
}

Upvotes: 0

Naveen
Naveen

Reputation: 73433

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.

Upvotes: 0

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361252

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

Upvotes: 3

Related Questions