Called function work at printf but not at arithmetic statement - c

I made a struct Triangle and I made a function to calculate p(perimeter/2).
When I call the function inside printf it works.
But when I call the same function as a simple arithmetic statement it doesn't work and gives me following error
called object 'p' is not a function or function pointer
Source code:
#include <stdlib.h>
typedef struct{
int a, b, c;
} Triangle;
int perimeter (Triangle t){
return t.a + t.b + t.c;
}
float p (Triangle t){
return perimeter(t) / 2.0;
}
int main() {
Triangle t = {3, 4, 5};
//float p = p(t);
printf("p = %.2f\n",p(t));
return 0;
}

//float p = p(t);
You cannot use the same name for a function and a variable. Change your float p to float a and it should work. Or rename your function to, say perimeter instead of just p.
Also in general, it is better to use slightly longer, clear and descriptive names for functions.

The line
float p = p(t);
defines a local variable p which shadows the global function p. This variable is of type float, so it is not a function or pointer.
Rename the variable to fix this.

Related

expected ‘double (*)(double)’ but argument is of type ‘double’ in C

I need help, am trying to calculate the integral of a function using trapezoidal rule in C.
I am trying to use a function as a variable in another function but I am having issues compiling, it gives the same message as the title.
Here's then Code
#include <stdio.h>
#include <math.h>
double test(double x){
return pow(x,2);
}
double tarpez(double a,double b, int n, double (*test)(double )){
/*x[n] represents the parameter
y[n] respresents the parameter ,a initial x,
h is the length of divided spaces*/
double h,x[n],y[n],So,Se;//So-- sum of odd, Se- ...even
h = (b-a)/n;
if (n%2==1){
n+=1;
}
for (int i ; i<=n;i++){
x[i]= a+i*h;
y[i] = test(x[i]);
printf("%lf\n",y[i] );
}
}
int main(void){
double x,a,b,fn;
int n;
fn =
tarpez(a,b,n,test(x));
}
Primo, double (*test)(double ) is type name like int or float. So you need declare double (*test)(double ) foo where foo is variable name (like int n).
Sceundo, name of type can't be name of function. Pointer of function need return tupe, args types and no-reserved name. So try double (*custom_name)(double ).
Tertio, in main function no tarpez(a,b,n,test(x)). Use tarpez(a,b,n,test); You use only name in this space.
PS
Try use typedef.

function pointer with variable inputs

In C, I am trying to pass a single-variable function into an optimization routine (optimization_routine). The optimization routine takes as input a pointer func1ptr to a function of a single float variable. However, I need to be able to pass multiple variables into this function. Thus, I am trying to construct a function pointer of one variable where all but the first inputs are "constants" into the function variable (sort of analogous to a partial derivative in calculus). I think I can do this with function pointers, but I can't figure out a syntax that makes sense.
That is, I have a function like this:
float function_all_inputs( float A, int B, float C, char D);
The optimization function requires a pointer like this:
typedef (*func1ptr)(float);
void optimization_function( func1ptr fp );
Thus, I want to construct a function of this form:
// create a function of A only at runtime using inputs B,C,D
func1ptr fp = ( & function_all_inputs(A,B,C,D))(A);
The function pointed to by fp should have the signature:
float function_one_input(float A);
Inputs B, C, and D are calculated elsewhere in the code, and thus are not known at compile-time; however, they are constant inside optimization_function.
I think I can do this in pure C using function pointers, however, I can't figure out the correct syntax. None of the examples I found online cover this case. Any advice you can provide would be appreciated.
It sounds like you are asking how to create a closure to capture parameters in C, and you can take a look at some options in the linked question.
However, without custom extensions, I think you will need to use global variables to achieve the effect you are looking for.
// Pass this wrapper with the name "wrapper" into the function
// that requires a function pointer
void wrapper(float a) {
// Where last four arguments are global variables that are computed first.
function_all_inputs(a, b, c, d, e);
}
// No need to create an explicit function pointer.
// Passing the name of the function is sufficient.
optimization_function(wrapper);
You need to write a wrapper function, like
int b;
float c;
char d;
int wrap(float a) {
return function_all_inputs(a, b, c, d);
}
Consider concurrency an re-entrancy though:
If multiple threads can use the wrapper, and need it to pass different data, make those globals thread-local:
_Thread_local int b;
If you need full re-entrancy, things get complicated:
You need to (also) save the variables before using a nested invocation with different parameters.
Writing a second (and maybe third) version of the wrapper using different globals may be better.
If you need more active at the same time, you can try a pool of those functions, though it gets unwieldy really fast. Better change your optimization-function by adding a context-parameter, and pass those extra-parameters with that.
For full freedom, you really need a way to write functions at runtime, at least enough to recover a context-pointer. That's not possible in pure C though.
If sizeof(float) >= sizeof(void*) on your platform, then you can "hack" it as follows:
typedef struct
{
float a;
int b;
float c;
char d;
}
params;
int function_all_inputs(float a, int b, float c, char d)
{
...
}
int function_one_input(float f)
{
params* p;
memcpy((void*)&p, (void*)&f, sizeof(void*));
return function_all_inputs(p->a, p->b, p->c, p->d);
}
int optimize()
{
float f;
params v;
params* p = &v;
v.a = ...;
v.b = ...;
v.c = ...;
v.d = ...;
memcpy((void*)&f, (void*)&p, sizeof(void*));
return optimization_function(function_one_input, f);
}
You weren't very consistent in your question about the return-value type, so I used int.
This may be overkill, but libffi supports creating closures in the following way:
#include <stdio.h>
#include <ffi.h>
typedef struct BCD { int B; float C; char D; } BCD;
void function_one_input_binding
(ffi_cif* cif, int* result, void** args, BCD* bcd) {
*result = function_all_inputs(*(float*)args[0], bcd->B, bcd->C, bcd->D);
}
int main() {
ffi_cif cif;
ffi_type* args[1];
ffi_closure* closure;
int (*function_one_input)(float);
// Allocate a closure.
closure = ffi_closure_alloc(sizeof(ffi_closure), &function_one_input);
// Tell libffi the parameter and return types.
args[0] = &ffi_type_float;
ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, &ffi_type_int, args);
// Bind closure data.
BCD bcd = { .B = 1, .C = 2.5, .D = 'x' };
ffi_prep_closure_loc(
closure, &cif, function_one_input_binding, &bcd, function_one_input);
// Call the function.
int result = function_one_input(42.5);
// Free the allocated closure.
ffi_closure_free(closure);
return 0;
}

C: Pointer after function call

I have to following C code:
a.b[(c+d(e,f,g)**i)]->j<-k
Now I have to add code to make it compile.
Most of that isn't a problem but what really irritates me is the d(e,f,g)**i part. **i as I understand is a pointer to a pointer, but I don't know how to handle it directly after a function call.
Just break it down:
d(e,f,g)**i
FunctionCall d with params e,f,g
Multiplied by
pointer-dereferce of i
Or:
d (e,f,g) * (*i)
Func. Params Multiply value-stored-at-pointer
Simple Enough
d(e,f,g) * *i // where d(e,f,g) is a function which should return a value and
*i is a pointer value
Eg if function d(e,f,g) returns 10 and if *i=5 then then output will be 10*5 = 50
Well this is relatively awful. Let's work from the inside out and remove things as we deal with them:
d is a function with 3 parameters. Let's assume it can return an int, and if it can't we'll deal with that later:
int e, f, g;
int d(int, int, int);
d(e,f,g) * *i will be fine if i is a pointer to an int.
int *i;
c + d(e,f,g) * *i will be fine if c is also an int.
int c;
So now we have the inside of the brackets completed. We also wanted that to be an integer so that it could work as an array notation. So we're good there. Let's rewrite the question without some of the stuff that we've resolved.
a.b[<some integer>]->j < -k
We can do the right side pretty easily.
int k;
This part is difficult to put into words, but I'm just walking the types. b is a double star because it's using array brackets followed by an -> sign.
struct {
struct {
int j;
} **b;
} a;
So we end up with:
#include <stdlib.h>
int main() {
int e, f, g;
int d(int e, int f, int g);
int *i;
int c;
int k;
struct {
struct {
int j;
} **b;
} a;
a.b[(c+d(e,f,g)**i)]->j<-k;
}

pointers to functions explanation in C

I don't quite understand the purpose of this. I have searched and read what seems to be the same thing on different sources, but none of them give an explanation as to what it does specifically and what is it's purpose.
can anyone help me understand this
Let's take a look in the Standard C library:
void qsort(void *BASE, size_t NMEMB, size_t SIZE,
int (*COMPAR)(const void *, const void *) );
the last argument of qsort is pointer to compare function. the compare function is used to compare two elements from the array (it defines the ordering).
If qsort() wouldn't be using function pointer we would have to write over and over again qsort() if we have different ordering requirement or new types/struct we would like to sort.
Take the following:
int i = 10;
A corresponding pointer can be defined like this:
int* p = &i;
Variable "p" is very similar to "i", in that they are both numbers. However, the value of 'p' is the memory address of variable 'i', in other words, it is the exact memory address where value 10 is stored. Furthermore, 'p' knows the type of the value at that memory address. It knows it is an "int", since it was defined as "int" + "star".
Similarly, consider a function:
int m(char* arg1, double arg2)
{
/* do something */
}
C provides the ability to access the memory address of where this function is stored. A function is not like a value, e.g. it cannot be changed, so when one says the memory address of a function, this actually means the memory address where the code of the function is located, e.g. whatever is written between the curly braces.
However, there is a similarity between a function and a variable. They both have a type. A function's type is comprised of:
Return Type
Parameter Type List, namely:
Type of parameter #1
Type of parameter #2
...
Type of parameter #N
C treats all functions that have the same return type and parameter type lists as "the same type of function". Similar to how two variables declared as "int i,j" are considered to be the same type, so are two functions with the same signature considered the same type.
The syntax for describing the type of a function includes the bare minimum: the return type and the types of each parameter (in the right order):
return-type (* <variable-name>)(Type-of-Param-1, Type-of-Param-2, ..., Type-of-Param-N)
In effect, in order to declare a pointer to function 'm' above:
int (*p)(char*, double) = &m;
"int" is the return type of method 'm', the fir pair of round brackets and the star are part of the syntax, 'p' is the variable name, "char*" is the type of the first parameter, and "double" is the tyep of the second parameter. There is no reference to the parameter names -- as the names of the parameters are not relevant to the type/signature of a function.
Note that similar to a variable, the address of a method is obtained exactly the same as for a variable, i.e. by prepending it with an ampersand.
Pointers to functions can be passed around simlar to pointers to variables, and more importantly, the code of the function at that particular memory address can be invoked. For example, in order to invoke function 'm' by means of pointer 'p', it would take something like this:
int result = p(NULL, 10.0);
int result = (*p) (NULL, 10.0); // alternative syntax
The typical example is a sorting function that needs you to "point" it to a function that can compare two elements. You pass this function a pointer to your comparison function so that it can call your function when it needs to do a comparison. You can't actually pass the function, but you can pass it a pointer to a function, which is just a variable that "points" to where your function is in memory. The sorting function can call your function by using this pointer. Pointers, in general, are just variables that store a memory address. That memory address is what it's "pointing" to, and it can be anything at that address - a function, an integer, a series of character variables that end with a null character. Function pointers are just variables that store the memory address of where a function is in memory so that the function can be called by some other piece of code.
Hope that explanation helps.
It is no more simple then this.
When you know how and why pointers work with normal variables, think of using these pointers, but this time with functions. That is, you replace the address of variables now with the address of the function, with all the power of pointers there, you can now access function indirectly by using the pointers that point to them instead of using their names directly.
From http://www.cplusplus.com/doc/tutorial/pointers/
// my first pointer
#include <iostream>
using namespace std;
int main ()
{
int firstvalue, secondvalue;
int * mypointer;
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}
And the output for the above is
firstvalue is 10
secondvalue is 20
Now from http://www.newty.de/fpt/intro.html#what
We have function pointers.
//------------------------------------------------------------------------------------
// 1.2 Introductory Example or How to Replace a Switch-Statement
// Task: Perform one of the four basic arithmetic operations specified by the
// characters '+', '-', '*' or '/'.
// The four arithmetic operations ... one of these functions is selected
// at runtime with a swicth or a function pointer
float Plus (float a, float b) { return a+b; }
float Minus (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
float Divide (float a, float b) { return a/b; }
// Solution with a switch-statement - <opCode> specifies which operation to execute
void Switch(float a, float b, char opCode)
{
float result;
// execute operation
switch(opCode)
{
case '+' : result = Plus (a, b); break;
case '-' : result = Minus (a, b); break;
case '*' : result = Multiply (a, b); break;
case '/' : result = Divide (a, b); break;
}
cout << "Switch: 2+5=" << result << endl; // display result
}
// Solution with a function pointer - <pt2Func> is a function pointer and points to
// a function which takes two floats and returns a float. The function pointer
// "specifies" which operation shall be executed.
void Switch_With_Function_Pointer(float a, float b, float (*pt2Func)(float, float))
{
float result = pt2Func(a, b); // call using function pointer
cout << "Switch replaced by function pointer: 2-5="; // display result
cout << result << endl;
}
// Execute example code
void Replace_A_Switch()
{
cout << endl << "Executing function 'Replace_A_Switch'" << endl;
Switch(2, 5, /* '+' specifies function 'Plus' to be executed */ '+');
Switch_With_Function_Pointer(2, 5, /* pointer to function 'Minus' */ &Minus);
}
As you will see from the above call, the address of Minus() function is passed which is then in passed on to call the actual function via pointer and in this case, pt2Func(...).
Note that in the case of function pointers you will take care of the function signature as well.
float (*pt2Func)(float, float)
float Minus (float a, float b) { return a-b; }
As you can see above, the signatures are the same, so you can pass in any function address and the call will work.
I hope this helps.
Function pointers are used to dynamicly call functions. You could for example take a function pointer as an argument to another function and in a sense provide additional functionality in that way. You could also create structs that have function pointers and thus a sort of member functions, like for classes. This could be usefull if you have a function that works on your structs but they can be a bit different in what work should actually be done with them. For example:
// Structures for our "objects"
typedef int funcPtr();
struct foo {
int a;
int b;
funcPtr* run;
}
struct bar {
int a;
int b;
funcPtr* run;
char* s;
}
// Functions that we will use as our "member functions"
int runOne() {
return 1;
}
int runTwo() {
return 2;
}
// Functions to create objects... kinda like new operators
struct foo* NewFoo(int aVal, int bVal) {
struct foo* this = (stuct foo*)malloc(sizeof(struct foo));
this->a = aVal;
this->b = bVal;
this->run = runOne;
return this;
}
struct bar* NewBar(int aVal, int bVal) {
struct bar* this = (stuct bar*)malloc(sizeof(struct bar));
this->a = aVal;
this->b = bVal;
this->run = runTwo;
return this;
}
// Create "objects"
struct foo* myFoo = NewFoo(10, 20);
struct bar* myBar = NewBar(30, 40);
// Run the run function on them (which actually runs different functions for each "object")
int result1 = myFoo->run();
int result2 = myBar->run();
result1 will now be 1 and result2 will be 2. This can be used if you have structs containing different kinds of "modules" with a similar interface but with different behavior for example.

How can I call a function using a function pointer?

Suppose I have these three functions:
bool A();
bool B();
bool C();
How do I call one of these functions conditionally using a function pointer, and how do I declare the function pointer?
You can do the following:
Suppose you have your A,B & C function as the following:
bool A()
{
.....
}
bool B()
{
.....
}
bool C()
{
.....
}
Now at some other function, say at main:
int main()
{
bool (*choice) ();
// now if there is if-else statement for making "choice" to
// point at a particular function then proceed as following
if ( x == 1 )
choice = A;
else if ( x == 2 )
choice = B;
else
choice = C;
if(choice())
printf("Success\n");
else
printf("Failure\n");
.........
.........
}
Remember this is one example for function pointer. there are several other method and for which you have to learn function pointer clearly.
I think your question has already been answered more than adequately, but it might be useful to point out explicitly that given a function pointer
void (*pf)(int foo, int bar);
the two calls
pf(1, 0);
(*pf)(1, 0);
are exactly equivalent in every way by definition. The choice of which to use is up to you, although it's a good idea to be consistent. For a long time, I preferred (*pf)(1, 0) because it seemed to me that it better reflected the type of pf, however in the last few years I've switched to pf(1, 0).
Declare your function pointer like this:
bool (*f)();
f = A;
f();
Initially define a function pointer array which takes a void and returns a void.
Assuming that your function is taking a void and returning a void.
typedef void (*func_ptr)(void);
Now you can use this to create function pointer variables of such functions.
Like below:
func_ptr array_of_fun_ptr[3];
Now store the address of your functions in the three variables.
array_of_fun_ptr[0]= &A;
array_of_fun_ptr[1]= &B;
array_of_fun_ptr[2]= &C;
Now you can call these functions using function pointers as below:
some_a=(*(array_of_fun_ptr[0]))();
some_b=(*(array_of_fun_ptr[1]))();
some_c=(*(array_of_fun_ptr[2]))();
bool (*FuncPtr)()
FuncPtr = A;
FuncPtr();
If you want to call one of those functions conditionally, you should consider using an array of function pointers. In this case you'd have 3 elements pointing to A, B, and C and you call one depending on the index to the array, such as funcArray0 for A.
You can declare the function pointer as follows:
bool (funptr*)();
Which says we are declaring a function pointer to a function which does not take anything and return a bool.
Next assignment:
funptr = A;
To call the function using the function pointer:
funptr();
Note that when you say:
bool (*a)();
you are declaring a of type "pointer to function returning bool and taking an unspecified number of parameters". Assuming bool is defined (maybe you're using C99 and have included stdbool.h, or it may be a typedef), this may or may not be what you want.
The problem here is that there is no way for the compiler to now check if a is assigned to a correct value. The same problem exists with your function declarations. A(), B(), and C() are all declared as functions "returning bool and taking an unspecified number of parameters".
To see the kind of problems that may have, let's write a program:
#include <stdio.h>
int test_zero(void)
{
return 42;
}
static int test_one(char *data)
{
return printf("%s\n", data);
}
int main(void)
{
/* a is of type "pointer to function returning int
and taking unspecified number of parameters */
int (*a)();
/* b is of type "pointer to function returning int
and taking no parameters */
int (*b)(void);
/* This is OK */
a = test_zero;
printf("a: %d\n", a());
a = test_one; /* OK, since compiler doesn't check the parameters */
printf("a: %d\n", a()); /* oops, wrong number of args */
/* This is OK too */
b = test_zero;
printf("b: %d\n", b());
/* The compiler now does type checking, and sees that the
assignment is wrong, so it can warn us */
b = test_one;
printf("b: %d\n", b()); /* Wrong again */
return 0;
}
When I compile the above with gcc, it says:
warning: assignment from incompatible pointer type
for the line b = test_one;, which is good. There is no warning for the corresponding assignment to a.
So, you should declare your functions as:
bool A(void);
bool B(void);
bool C(void);
And then the variable to hold the function should be declared as:
bool (*choice)(void);
bool (*fptr)();
int main(void)
{
...
...
printf("Enter your choice");
scanf("%d",&a);
switch(a)
{
case 0:
fptr = A;
break;
case 1:
fptr = B;
break;
case 2:
fptr = C;
break;
case 3:
break;
}
(*fptr)();
return 0;
}
Your choice is stored in a. Then accordingly, functions are assigned in the function pointer. Finally, depending on your choice, the very same function is called to return the desired result.
The best way to read that is the clockwise/spiral rule by David Anderson.
Calling a function through a function pointer
float add(int, float), result;
int main()
{
float (*fp)(int, float);
float result;
fp = add;
result = add(5, 10.9); // Normal calling
printf("%f\n\n", result);
result = (*fp)(5, 10.9); // Calling via a function pointer
printf("%f\n\n", result);
result = (fp)(5, 10.9); // Calling via function pointer. The
// indirection operator can be omitted
printf("%f", result);
getch();
}
float add(int a, float b)
{
return a+b;
}
>
Output
15.90000
15.90000
15.90000
You declare a function pointer variable for the given signature of your functions like this:
bool (* fnptr)();
you can assign it one of your functions:
fnptr = A;
and you can call it:
bool result = fnptr();
You might consider using typedefs to define a type for every distinct function signature you need. This will make the code easier to read and to maintain. i.e. for the signature of functions returning bool with no arguments this could be:
typdef bool (* BoolFn)();
and then you can use like this to declare the function pointer variable for this type:
BoolFn fnptr;
Slightly different approach:
bool A() {...}
bool B() {...}
bool C() {...}
int main(void)
{
/**
* Declare an array of pointers to functions returning bool
* and initialize with A, B, and C
*/
bool (*farr[])() = {A, B, C};
...
/**
* Call A, B, or C based on the value of i
* (assumes i is in range of array)
*/
if (farr[i]()) // or (*farr[i])()
{
...
}
...
}
If you need help with complex definitions, like
double (*(*pf)())[3][4];
take a look at my right-left rule here.
//Declare the pointer and asign it to the function
bool (*pFunc)() = A;
//Call the function A
pFunc();
//Call function B
pFunc = B;
pFunc();
//Call function C
pFunc = C;
pFunc();
I usually use typedef to do it, but it may be overkill, if you do not have to use the function pointer too often..
//assuming bool is available (where I come from it is an enum)
typedef bool (*pmyfun_t)();
pmyfun_t pMyFun;
pMyFun=A; //pMyFun=&A is actually same
pMyFun();
This has been more than adequately answered, but you may find this useful: The Function Pointer Tutorials. It is a truly comprehensive treatment of the subject in five chapters!

Resources