definition pointer variable - c++

i can't understand following defining pointer variable. can you help me?
double(*)(double *) foo;
note : sory, i edit name of variable func to foo.

This is not valid C. Perhaps you mean this:
double(*func)(double *);
which declares func as a pointer to a function that takes a pointer-to-double, and returns a double.
You can use http://cdecl.org for this sort of thing.

Try this (tested):
// functions that take double * and return double
double dfunc(double *d) { return (*d) * 2.0; }
double tfunc(double *d) { return (*d) * 3.0; }
int main()
{
double val = 3.0;
double // 3. the function returns double
(*pFunc) // 1. it's a pointer to a function
(double *); // 2. the function takes double *
pFunc = dfunc;
printf("%f\n", pFunc(&val)); // calls dfunc()
pFunc = tfunc;
printf("%f\n", pFunc(&val)); // calls tfunc()
}
Output:
6.000000
9.000000

it's a pointer to a function returning double having a parameter of type pointer to double, if you correct the variable declaration since as it stands its just incorrect correct syntax would be double (*foo) (double*)
uses are polymorphism by being able to replace a function:
struct memory_manager{
void*(*getmem)(size_t);
void(*freemem)(void*);
}mem_man;
void* always_fail(size_t){return 0;}
void* myalloc(size_t s){
void* p=mem_man.get_mem(s);
if(p) return p;
mem_man.getmem=always_fail;
return 0;
}
void myfree(void* p){
if(p) freemem(p);
}
it's not really the c++-way i geuss, since for most purposes inheritance and virtual functions offer a better solution, but if you're restricted to c, then you can use this technique to simulate virtual functions.

Related

Pointer to member function of an object [duplicate]

This question already has answers here:
Function pointer to member function
(8 answers)
Closed 5 years ago.
I would like to integrate a function with gsl. Therefor I have to define a function f (the integrant, which has to be of the form double (*)(double, void*)). For the call of the gsl integration method I need to define a struct, which contains a pointer to a function (this struct is called gsl_function).
gsl_function F;
F.function = &MyClass::my_f;
The function f must be implemented in a class (in the same class from which the integration procedure should be called). How can I assign the pointer above correctly, since the 2nd line is not compiling and leads to the error:
cannot convert ‘double (MyClass::*)(double, void*)’ to ‘double (*)(double, void*)’ in assignment.
Here the definition of my_f
struct my_f_params { double a; double b;};
double my_f (double x, void * p) {
struct my_f_params * params = (struct my_f_params *)p;
double a = (params->a);
double b = (params->b);
return 1.0/(sqrt(a * (1.0 + x)*(1.0 + x)*(1.0 + x) + (1-a) * std::pow((1.0 + x), (3.0 * (1.0 + b)))));
}
which has to be of the form double (*)(double, void*)
Non static member function declarations involve the implicit call scope qualifier as stated in the error message
double (MyClass::*)(double, void*)
// ^^^^^^^^^
This is different from the callback function pointer definition.
What you probably can do with such interface, is to pass the this pointer through the void* argument of the callback function:
class MyClass {
static double func(double d,void* thisPtr) {
MyClass* myClass = (MyClass*)thisPtr;
// do something
}
};
As mentioned in the documentation you can set the params like that in a wrapper class:
class gsl_function_wrapper {
public:
gsl_function_wrapper() {
F.function = &func;
F.params = this;
}
private:
gsl_function F;
double a;
double b;
static double func(double d,void* thisPtr) {
gsl_function_wrapper* myWrapper = (gsl_function_wrapper*)thisPtr;
// do something with a and b
foo(d,myWrapper->a,myWrapper->b);
}
};

operator= overload in C++

I need some help with operator assignment. This is code:
Sinusoid.h:
class Sinusoid : public Component
{
float fs, f, A, fi;
int N;
double *array;
public:
Sinusoid(float fs, float f, float Ts, float fi, float A);
void count(int type=1);
void clear();
~Sinusoid();
double *getArray() { return this->array; }
double*& operator=(Sinusoid* const &rhs) {
return rhs->array;
};
};
main.cpp:
#include "headers.h"
int main()
{
int N = 1000 * 2.5;
Sinusoid *sinus = new Sinusoid(1000, 15, 2.5, (M_PI / 4), 0.7);
double **answers = new double*[7];
for (int i = 0; i < 7; i++) {
answers[i] = new double[N];
}
//lab1
//Zad1
sinus->count(1);
answers[0] = sinus;
return 0;
}
When i build this code i've got the following problem:
C2440 '=': cannot convert from 'Sinusoid *' to 'double *' main.cpp:15
I know that i can assign two classes with overloaded operator "=" but i want to take a private member of class (double *array;). I know that i can do it by "getArray()" method but i want to learn more "beautiful" practice. Hope you will help me.
Thank you.
Your double*& operator=(Sinusoid* const &rhs) operator doesn't do what you apparently think it does.
An operator= member function allows you to have an instance of the class (Sinusoid) on the left side of an assignment and an instance of the parameter type (Sinusoid*) on the right side. So what you wrote would let you do:
Sinusoid* pointer = whatever;
Sinusoid object;
object = pointer;
Obviously that's not what you intended. (And probably not something you'll ever want.)
The return type of the operator= doesn't have any influence on this fundamental usage. All it means is that the result of object = pointer is then a double*&. So it would let you write:
double* foo;
foo = (object = pointer);
And that's still not helpful for what you want.
Since answers[0] is a pointer, there's no way to create a custom assignment operator for it. However the language has a different mechanism which can be used here. You can create an implicit conversion operator for your class so that compiler is allowed to convert/decay it into a different type when reasonable. Try adding the following to your class:
operator double* () {
return rhs->array;
}
That should work for the case you want.
Although personally I don't think there's anything wrong with leaving the usage to require calling getArray() in the first place. Sometimes the clarity of an explicit function call can make it easier to read what's actually going on.
Try...
class Sinusoid : public Component {
...
operator double*() {
return array;
}
and the usage
answers[0] = *sinus;

Output dynamic array from a function pointer

I'm very new to pointers so please bear with me...
My code defines a function for the multiplication of two matrices (matrixMultiplication). I have then defined a function pointer to this function.
#include <iostream>
void matrixMultiplication (const double A[3][3], const double B[3][3], double output[3][3])
{
int i, j, k;
for (i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
output[i][j]+=A[i][k]*B[k][j];
}
}
}
}
double (*matrixMultiplication (const double (*left)[3], const double (*right)[3]))[3]
{
double output[3][3];
matrixMultiplication(left, right, output);
}
int main ()
{
using namespace std;
double A[3][3]={{1,1,1},{1,1,1},{1,1,1}};
double B[3][3]={{1,1,1},{1,1,1},{1,1,1}};
cout<<"The function returns..."<<endl;
double print[3][3]=matrixMultiplication(A,B);
int i, j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
cout<<print[i][j]<<"\t";
}
cout<<"\n";
}
return 0;
}
What I want to do is output the array given by the pointer function, *matrixMultiplication, using a for loop (just for aesthetic purposes). I have played around with the code and ended up with initialiser or segmentation (11) errors. I feel like I'm missing something blatantly obvious given I'm new to C++...
Any ideas would be most welcome!
The problem is with:
double (*matrixMultiplication (const double (*left)[3], const double (*right)[3]))[3]
{
double output[3][3];
matrixMultiplication(left, right, output);
}
I don't know what it is and neither does my compiler! ;)
Using functional, a matrixMultiplication function type can be defined and used, like so:
#include <functional> // or <tr1/functional>
// type
typedef function<void (const double[3][3], const double[3][3], double[3][3])> MatrixFunction;
// instance
MatrixFunction matrixFunctionPtr(&matrixMultiplication);
// call
matrixFunctionPtr(A,B,print);
Note: you also need to declare your output array double print[3][3]; * before* you call the matrixMultiplication function...
You have a function:
void matrixMultiplication (const double A[3][3], const double B[3][3], double output[3][3])
{
...
}
This function works. It takes three arrays as arguments (which is to say it takes three pointers-- this is a subtle point, and I don't think it's a good exercise for a beginner because it clouds the distinction between passing by value and passing by reference -- but never mind that for now) and returns void (i.e. nothing), and . Now you want to construct a function pointer that points to this function. But this:
double (*matrixMultiplication (const double (*left)[3], const double (*right)[3]))[3]
{
...
}
is not a function pointer; it's a function that returns a pointer to an array of double, but it has some internal errors (and don't even worry about what it takes as arguments for now).
Let's do a simpler example first:
double foo(int n) // function
{
return(3);
}
int main()
{
double (*bar)(int); // function pointer
bar = &foo;
double z = (*bar)(5);
cout << z << endl;
return(0);
}
Now that we see how function pointers work, we apply one to matrixMultiplication:
void (*matFP)(const double A[3][3], const double B[3][3], double output[3][3]);
matFP = &matrixMultiplication;
double C[3][3];
(*matFP)(A,B,C);

Curiosity about passing a function as parameter - C++

suppose you have the following method:
double * myMethod(double (*f)(double[]), double *x, int size)
{
//do something and return
}
Why can't I write as follows?
double * myMethod(double (*f)(double *), double *x, int size)
{
//do something and return
}
replacing the [] with * ?
You can, but because arrays deprecate the pointers, they actually have the same signature, so if you're getting an error it's because you're trying to redefine the function:
http://ideone.com/E1Z7B works because I renamed the second function.

C++ typedef declaration

Can you please explain what does the following line means?
typedef int (*Callback)(void * const param,int s)
It means that Callback is a new name for the type : pointer to a function returning an int and taking two parameters of type 'const pointer to void' and 'int'.
Given a function f :
int f(void * const param, int s)
{
/* ... */
}
The Callback can be used to store a pointer to f :
Callback c = &f;
The function f can be later invoked through the pointer without directly referring to its name :
int result = c(NULL, 0);
At the point of the call, the name f does not appear.
It creates a new "alias" or name by which you can refer to pointers to functions that return int and take two parameters: a void* const and an int. You can then create variables of that type, assign to them, invoke the function through them etc as in:
int fn(void * const param,int s) { ... }
Callback p;
p = fn;
int x = p(NULL, 38);
Note that typedefs do not really create new types... every equivalent typedef is resolved to the single real type for the purposes of overload resolution, template instantiation etc..
It declares a function type:
// Set up Callback as a type that represents a function pointer
typedef int (*Callback)(void * const param,int s);
// A function that matches the Callback type
int myFunction(void* const param,int s)
{
// STUFF
return 1;
}
int main()
{
// declare a variable and assign to it.
Callback funcPtr = &myFunction;
}