Home > Enterprise >  Passing a pointer to a vector
Passing a pointer to a vector

Time:09-08

I'm exploring a c library and cant figure out why its examples are written as they are. In the example they do the following

 std::vector<unsigned int> vec(count);
 someFunc(&vec[0]);  

while the fucion is define as

void someFunc(unsigned int* a);

why are the examples passing a reference to the first element of the vector and not the whole vector. Inst this code the same ?

 someFunc(&vec);  

Edit: I should have provided more contex. I simplified the case, but this has proven a bad descision. The function is supposed to simplify a mesh, the vec is a list of all the indicies of the mesh. Presumably somewhere in the code that pointer is used to iterate over the rest of the indicies ?

CodePudding user response:

It is likely that the library function someFunc was written with a C-style array as an argument, i.e. you just pass a pointer to the first element (not a reference). As the pointer is typed, the addresses of the next elements can be computed by the function. But their number must be known elsehow.

CodePudding user response:

The reason they have written their example like they have is that someFunc() takes in a unsigned int* type (a pointer to an unsigned int). The reason they call it as:

someFunc(&vec[0]);

and not

someFunc(&vec);

is because a std::vector is not like a C-style array (say unsigned int arr[]) where arr can be boiled down a unsigned int* to the first element in the array but is rather a class/struct that acts as a resource handle to some dynamic memory they you access std::vector interface. Thus, like any class in C , calling foo(&A) (where A is some class instance/object) would return a pointer to the object itself [1].

In their example they have accessed the first element of the vec like a C-style array (using the overloaded operator[]) which is a reference. They then use the C-style unary-prefix ampersand operator (with the signature &A) to access the address of the value obtained through the index operator.

There example might be clearer if they used std::vector::data() which returns a pointer to the starting address of the memory owned by the vector or using std::addressof() (although the latter can be verbose).

someFunc(vec.data());

/// or ...

someFunc(std::addressof(vec[0]));

[1] Note: This may not be the case if the class/struct in question has overloaded the & operator to behave differently. std::vector does not in this case.

Links

  •  Tags:  
  • c
  • Related