I have a callback function that takes a void * as a parameter to pass arguments to and I'd like to pass a vector to the function. The function will be called multiple times so after the callback process is complete, I'd like to be able to iterate over all the elements that have been push_back()'ed through the callback.
static void cb(void *data)
{
vector<int> *p = static_cast<vector<int>*>(data); //Attempting to convert *void to vector<int>
p->push_back(1);
}
int main()
{
vector<int> a(10); //Max of 10 push_back()s? vector<int> a; gives memory error.
cb((void*)&a.at(0));
cout << a.at(0); //Gives a random number of 6 digits or higher
}
The issue is that it does not properly have a value of "1" when a.at(0) is called after the callback, just some random number.
Assuming that you cannot change the signature of cb(), try this:
cb(static_cast<void*>(&a));
Here:
cb ((void*)&a.at(0));
you pass a pointer to the first element of the vector, not the vector itself, but here:
vector <int> *p = static_cast <vector <int> *> (data);
you cast passed data to the pointer to a vector, which is probably undefined behavior. If you want to pass pointer to the whole vector, pass like this:
cb ((void *)&a);
If you really want to pass a pointer to an element of the vector, then you should cast like this:
int * = static_cast <int *> (data);
In C++11, you have vector::data:
cb(a.data());
Related
Arrays of function pointers can be created like so:
typedef void(*FunctionPointer)();
FunctionPointer functionPointers[] = {/* Stuff here */};
What is the syntax for creating a function pointer array without using the typedef?
arr //arr
arr [] //is an array (so index it)
* arr [] //of pointers (so dereference them)
(* arr [])() //to functions taking nothing (so call them with ())
void (* arr [])() //returning void
so your answer is
void (* arr [])() = {};
But naturally, this is a bad practice, just use typedefs :)
Extra:
Wonder how to declare an array of 3 pointers to functions taking int and returning a pointer to an array of 4 pointers to functions taking double and returning char? (how cool is that, huh? :))
arr //arr
arr [3] //is an array of 3 (index it)
* arr [3] //pointers
(* arr [3])(int) //to functions taking int (call it) and
*(* arr [3])(int) //returning a pointer (dereference it)
(*(* arr [3])(int))[4] //to an array of 4
*(*(* arr [3])(int))[4] //pointers
(*(*(* arr [3])(int))[4])(double) //to functions taking double and
char (*(*(* arr [3])(int))[4])(double) //returning char
:))
Remember "delcaration mimics use". So to use said array you'd say
(*FunctionPointers[0])();
Correct? Therefore to declare it, you use the same:
void (*FunctionPointers[])() = { ... };
Use this:
void (*FunctionPointers[])() = { };
Works like everything else, you place [] after the name.
I've been building a game engine and have found that I needed dynamically allocated arrays of function pointers.
To address this simply, I've opted for encapsulating the function pointers inside a class.
Here's a simple example:
class Function{
private:
public:
int (*sampleFunction)(int);
};
static int returnInt(int val){
int ret = 20 * i;
return ret;
}
int main(void){
Function *functions; /* V put yours here V */
size_t functionCount = getFunctionCount();
functions = new Function[functionCount];
for(int i=0; i<functionCount; i++)
functions[i].sampleFunction = &returnInt;
for(int i=0; i<functionCount; i++)
functions[i].sampleFunction(i);
return 0;
}
Where can this be useful?
Say that you have a graphical application that you're building that creates buttons out of an undefined number of files in a directory.
Each button has a unique "hitbox" coordinate relative to it's position in an array, and you need to be able to uniquely handle a mouse click for each button.
The Functions class is meant to be placed inside another, more complex, class. Where the point of the function pointer is to make it easier to redefine the button click event when different algorithms are required for the same "form element".
As the title describes, I am trying to pass the pointer to the data of a std::vector into a function expecting a double pointer. Take as an example the code below. I have an int pointer d which is passed to myfunc1 as &d (still not sure if call it the pointer's reference or what), where the function changes its reference to the beginning of an int array filled with 1,2,3,4. However, if I have a std::vector of ints and try to pass &(vec.data()) to myfunc1 the compiler throws the error lvalue required as unary ‘&’ operand. I have already tried something like (int *)&(vec.data()) as per this answer, but it does not work.
Just for reference, I know I can do something like myfunc2 where I directly pass the vector as reference and the job is done. But I want to know if it's possible to use myfunc1 with the std::vector's pointer.
Any help will be very much appreciated.
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
void myfunc1(int** ptr)
{
int* values = new int[4];
// Fill all the with data
for(auto& i:{0,1,2,3})
{
values[i] = i+1;
}
*ptr = values;
}
void myfunc2(vector<int> &vec)
{
int* values = new int[4];
// Fill all the with data
for(auto& i:{0,1,2,3})
{
values[i] = i+1;
}
vec.assign(values,values+4);
delete values;
}
int main()
{
// Create int pointer
int* d;
// This works. Reference of d pointing to the array
myfunc1(&d);
// Print values
for(auto& i:{0,1,2,3})
{
cout << d[i] << " ";
}
cout << endl;
// Creates the vector
vector<int> vec;
// This works. Data pointer of std::vector pointing to the array
myfunc2(vec);
// Print values
for (const auto &element : vec) cout << element << " ";
cout << endl;
// This does not work
vector<int> vec2;
vec2.resize(4);
myfunc1(&(vec2.data()));
// Print values
for (const auto &element : vec2) cout << element << " ";
cout << endl;
return 0;
}
EDIT: What my actual code does is to read some binary files from disk, and load parts of the buffer into the vector. I was having troubles getting the modified vector out of a read function, and this is what I came up with that allowed me to solve it.
When you write:
myfunc1(&(vec2.data()));
You are getting the address of a rvalue. The pointed int* is so a temporary that is destroyed right after the call.
This is why you get this error.
But, as #molbdnilo said, in your myfunc1() function, you are reassigning the pointer (without caring to destroy previously allocated memory by the way).
But the std::vector already manages its data memory on its own. You cannot and you must not put your hands on it.
What my actual code does is to read some binary files from disk, and load parts of the buffer into the vector.
A solution could be to construct your std::vector by passing the iterator to the beginning and the iterator to the end of the desired part to extract in the constructor's parameters.
For example:
int * buffer = readAll("path/to/my/file"); // Let's assume the readAll() function exists for this example
// If you want to extract from element 5 to element 9 of the buffer
std::vector<int> vec(buffer+5, buffer+9);
If the std::vector already exists, you can use the assign() member function as you already did in myfunc2():
vec.assign(buffer+5, buffer+9);
Of course in both cases, you have to ensure that you are not trying to access an out of bounds element when accessing the buffer.
The problem is that you cannot take the address of data(), since it is only a temporary copy of the pointer, so writing to a pointer to it makes not that much sense. And that is good that way. You DO NOT want to pass data() to this function since it would overwrite the pointer with a new array and that would break the vector. You can remove one * from the function and only assign to it and not allocate the memory there. This will work, but make sure to allocate the memory in the caller (with resize, just reserve will result un undefined behavior, since data() is only a pointer to the beginning of the valid range [data(), data() + size()). The range [data(), data() + capacity ()) is not necessary valid.
I was playing through c++ and trying to understand vector and its signature .
In below method printPrimes I need to use pointer with address of why ?
Is vector<int> &primes not enough as from main method printPrimes is already sending address .
void printPrimes(long long l, long long r, vector<int>* &primes) {
// some code
}
vector<int>* sieve() {
vector<int> *prime = new vector<int>();
return prime;
}
int main() {
vector<int> *primes = sieve();
printPrimes(l, r, primes);
return 0;
}
I need to use pointer with address of
Here, & does not mean "address of"; it means the type "reference to".
It's clearer if you write it not like this:
vector<int>* &primes
but like this:
vector<int>*& primes
Though the choice of whitespace is artificial, that better documents that this & is "part of the type".
Have some types:
std::vector<T> = A vector of Ts
std::vector<T>& = A reference to a vector of Ts
std::vector<T>* = A pointer to a vector of Ts
std::vector<T>*& = A reference to a pointer to a vector of Ts
std::vector<T>*** = A pointer to a pointer to a pointer to a vector of Ts
std::vector<T>**& = A reference to a pointer to a pointer to a vector of Ts
…and so forth.
As for why you need a vector<int>*& for printPrimes to do its job, we could not tell you without actually being able to see it. I will say that it seems unlikely it needs a pointer at all, and that if it wants to modify that pointer it's going to cause problems with the new and delete in the calling scope.
In fact, all that dynamic allocation is completely pointless and only complicates things.
The following was likely intended instead:
void printPrimes(long long l, long long r, vector<int>& primes) {
// some code
}
vector<int> sieve() {
vector<int> prime;
return prime;
}
int main() {
vector<int> primes = sieve();
printPrimes(l, r, primes);
}
vector<int>* &primes parameter has to be read this way:
Reference to a pointer of vector of int
and not
Address of a pointer of vector of int (which, you are right, would be useless)
Passing by reference allows to directly manipulate any instance outside of scope (like with pointers, but a safer way since a reference cannot be nullptr, and its existence is auto-managed (no need to delete)).
In c++ & in function parameter used to pass parameter by reference. vector<int>* &primes declares primes to be a reference to a pointer to vector<int>.
If printPrimes means to print only the vector passed to the function then the signature
void printPrimes(long long l, long long r, vector<int> &primes);
can also do the job.
Reference to a pointer is needed when the pointer passed to the function is need to be modified and it's effect is expected to seen in the caller function.
void foo(int*& p){
p = new int[10];
// rest of the code
}
if a function bar is calling foo like
void bar(/* some parameters */){
// ...
int *p;
foo(p);
// rest of the code
}
foo is modifying the pointer itself and this modification will be seen to bar also and memory allocated to p can be accessed from bar.
so let's say there is a function int* coeff(int n) that returns array (or rather, address to array[0]). Now, in this function this array has length of let's say 5, but when I call it like: int* array=SomeObject->coeff(n); that size is lost, and I don't know how can I get it back again. Any help please?
If you actually return a locally declared you have bigger problem than "losing its size".
First of all you have to remember that arrays decays to pointers, and once it has done that you no longer have any information about the array, just the pointer. And the size of a pointer is the size of the pointer and not what it points to.
The bigger problem might be you returning a locally declared array. When a function returns all variables declared locally in it goes out of scope. So what does the returned pointer then point to?
I assume your code looks something like this:
int* coeff(int n)
{
int* a = new int[5];
// ...
return a;
}
I suggest using a vector instead of an array:
#include <vector>
std::vector<int> coeff(int n)
{
std::vector<int> a(5);
// ...
return a;
}
You can always get the size of a vector by calling the .size() member function:
int main()
{
std::vector<int> x = coeff(42);
std::cout << x.size() << " elements in the vector!\n";
}
Arrays of function pointers can be created like so:
typedef void(*FunctionPointer)();
FunctionPointer functionPointers[] = {/* Stuff here */};
What is the syntax for creating a function pointer array without using the typedef?
arr //arr
arr [] //is an array (so index it)
* arr [] //of pointers (so dereference them)
(* arr [])() //to functions taking nothing (so call them with ())
void (* arr [])() //returning void
so your answer is
void (* arr [])() = {};
But naturally, this is a bad practice, just use typedefs :)
Extra:
Wonder how to declare an array of 3 pointers to functions taking int and returning a pointer to an array of 4 pointers to functions taking double and returning char? (how cool is that, huh? :))
arr //arr
arr [3] //is an array of 3 (index it)
* arr [3] //pointers
(* arr [3])(int) //to functions taking int (call it) and
*(* arr [3])(int) //returning a pointer (dereference it)
(*(* arr [3])(int))[4] //to an array of 4
*(*(* arr [3])(int))[4] //pointers
(*(*(* arr [3])(int))[4])(double) //to functions taking double and
char (*(*(* arr [3])(int))[4])(double) //returning char
:))
Remember "delcaration mimics use". So to use said array you'd say
(*FunctionPointers[0])();
Correct? Therefore to declare it, you use the same:
void (*FunctionPointers[])() = { ... };
Use this:
void (*FunctionPointers[])() = { };
Works like everything else, you place [] after the name.
I've been building a game engine and have found that I needed dynamically allocated arrays of function pointers.
To address this simply, I've opted for encapsulating the function pointers inside a class.
Here's a simple example:
class Function{
private:
public:
int (*sampleFunction)(int);
};
static int returnInt(int val){
int ret = 20 * i;
return ret;
}
int main(void){
Function *functions; /* V put yours here V */
size_t functionCount = getFunctionCount();
functions = new Function[functionCount];
for(int i=0; i<functionCount; i++)
functions[i].sampleFunction = &returnInt;
for(int i=0; i<functionCount; i++)
functions[i].sampleFunction(i);
return 0;
}
Where can this be useful?
Say that you have a graphical application that you're building that creates buttons out of an undefined number of files in a directory.
Each button has a unique "hitbox" coordinate relative to it's position in an array, and you need to be able to uniquely handle a mouse click for each button.
The Functions class is meant to be placed inside another, more complex, class. Where the point of the function pointer is to make it easier to redefine the button click event when different algorithms are required for the same "form element".