I want to rewrite some code that uses a lot of unsigned char
arrays, to instead make use of std::vector<unsigned char>
objects. The problem I have is that these are currently used to store the data that will be written to either a serial port or socket write buffer and the library functions to do this take either void*
or unsigned char*
. An example of such a function is
WriteToSocketBuffer(unsigned char* pBuffer, int iSize);
so currently I have code of the form
unsigned char* pArray = new unsigned char[iSize];
// populate array with data
WriteToSocketBuffer(pArray,iSize);
delete [] pArray;
My question is the following: If I change my class to have a std::vector<unsigned char>
instead of a raw array can I simply call my library function using
std::vector<unsigned char> myVector;
WriteToSocketBuffer(&myVector[0],myVector.size());
Does passing the address of the first element in the vector act in the same was as passing in the address of the first element in a raw array. Is it this simple?
How Arrays are Passed to Functions in C/C++? A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name. In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun().
A common misconception is that an array and a pointer are completely interchangeable. An array name is not a pointer. Although an array name can be treated as a pointer at times, and array notation can be used with pointers, they are distinct and cannot always be used in place of each other.
Consider this example: int *ptr; int arr[5]; // store the address of the first // element of arr in ptr ptr = arr; Here, ptr is a pointer variable while arr is an int array. The code ptr = arr; stores the address of the first element of the array in variable ptr .
In the case of passing a vector as a parameter in any function of C++, the things are not different. We can pass a vector either by value or by reference.
Yes, The elements of a vector are assured to be contiguous similar to an array.
Reference:
C++03 Standard: [lib.vector] 23.2.4 Class template vector
......
The elements of a vector are stored contiguously, meaning that ifv
is avector<T, Allocator>
whereT
is some type other thanbool
, then it obeys the identity&v[n] == &v[0] + n
for all0 <= n < v.size()
C++98 didn't mandate contiguous allocation for the data in an std::vector
, but that's what all known implementations did anyway.
As of C++03, that was standardized as a requirement, so it's now required, not just how things happen to be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With