Qiu
Qiu

Reputation: 5751

Vector as an argument (int**) to function

If I have function declared as, e.g.:

void f1(int* a);

and simple vector: std::vector<int> v - I can use this vector as an input to this function:

f1(&v[0]);

But what if I have function f2, e.g.:

void f2(int** a);

and another vector: std::vector<int> *v. How can I use it with vector data?

Currently I have a dynamically allocated table, which use function f2 (f2(&tab,tablength)). It works fine, but I have to additionally send tablength. Because I'm now changing logic of my program a little bit, I've figured I can use vectors instead of classic tables (because I need an arrays that can change in size). But I stacked. To put it in a nutshell, f2 is a function that implements multiplying table tab by some constant value in GF(2^8).

Upvotes: 2

Views: 260

Answers (3)

LihO
LihO

Reputation: 42083

void f1(int* a); is a function that expects an address of memory, where an int is stored and in this case (based on usage: f1(&v[0]);) it is the first element of an array, elements of which this function will modify.

On the other hand, void f2(int** a); expect a pointer to pointer to first element, meaning that the function will most likely try to change the pointer itself. In case of an array, function of this kind would most likely reallocate the array (change its size) or deallocate it completely. In that case, trying to do something like int *p = &v[0]; f2(&p); will yield undefined behavior.

Clean and semantically correct solution would be changing the f2 function to take the reference to the vector instead: void f2(std::vector<int>& v). Passing the vector object by reference will allow this function to change its elements but also the vector itself with respect to the lifetime of the object passed to it. (One of the greatest consequences of this will be complete removal of the ugly memory management that would be necessary otherwise.)

Upvotes: 1

Mats Petersson
Mats Petersson

Reputation: 129314

You COULD do :

int *p = &(*v)[0]; 

f2(&p); 

however, that is PROBABLY not what you want to do. Unfortunately, without understanding how f2 actually uses the int **a argument, it's hard to say what is the right thing to do - perhaps implement a second f2(std::vector<int>& av) function?

Edit: Seeing the edited question, I would suggest that you use f2(std::vector<int>& av), and get rid of the f2(int **) variant.

Upvotes: 3

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70931

A vector and a pointer to pointer are different things. You will have to implement logic to convert from one to the other.

You will have to allocate a dynamic array and copy the data from the vector to it before passing this array as argument to f2. You will also have to add another argument to pass the size of the array.

Upvotes: 4

Related Questions