Function pointer to different functions with different arguments in C - c

I have two functions with variable number and types of arguments
double my_func_one(double x, double a, double b, double c) { return x + a + b + c }
double my_func_two(double x, double p[], double c) { return x + p[0] + p[1] + c }
I want to use a pointer to a function to the functions I defined above based on a some condition getting true e.g.
if (condition_1)
pfunc = my_func_one;
else if (condition_2)
pfunc = my_func_two;
// The function that will use the function I passed to it
swap_function(a, b, pfunc);
My question is, for this scenario, Can I at all define a function pointer? If yes, how?
My understanding is that the prototype of function pointer should be the same for all those functions it CAN be pointed to.
typedef double (*pfunction)(int, int);
In my case they are not the same. Is there any other way to do this?
Language
I am developing in C and I am using gcc 4.4.3 compiler/linker

The cleanest way to do it is to use a union:
typedef union {
double (*func_one)(double x, double a, double b, double c);
double (*func_two)(double x, double p[], double c);
} func_one_two;
Then you can initialize an instance of the union, and include information to the swap_function function to say which field is valid:
func_one_two func;
if (condition_1)
func.func_one = my_func_one;
else if (condition_2)
func.func_two = my_func_two;
// The function that will use the function I passed to it
swap_function(a, b, func, condition_1);
This assumes that swap_function can know based on condition_1 being false that it should assume condition_2. Note that the union is passed by value; it's only a function pointer in size after all so that's not more expensive than passing a pointer to it.

My question is, for this scenario, Can I at all define a function pointer?
No. (Other than by dirty typecasting.)
Is there any other way to do this?
Your best bet is to create a wrapper function for one of your existing functions. For example:
double my_func_one_wrapper(double x, double p[], double c) {
return my_func_one(x, p[0], p[1], c);
}
That way, you have two functions with the same signature, and therefore the same function-pointer type.

An old topic but I am facing same issue and finally came with this idea.
If you want the same prototype for each functions you can wrap the parameters in structure like this :
typedef struct {
double a,
b,
c;
}chunk1_t;
typedef struct {
double p[];
double c;
}chunk2_t;
Then your function pointer becomes:
double (*pfunc) (double x, void *args);
which leads to something like this :
pfunc cb;
double swap_function(double x, pfunc cb, void *args);
double my_func_one(double x, void *args) {
chunk1_t *chunk = (chunk1_t*) args;
return x + chunk->a + chunk->b + chunk->c;
}
double my_func_two(double x, void *args) {
chunk2_t *chunk = (chunk2_t*) args;
return x + chunk->p[0] + chunk->p[1] + chunk->c ;
}
int main(){
// declare a, b,...
double a = 1.0f;
//...
// cast for safety
chunk1_t myChunk1 = {(double)a, (double)b, (double)c};
// don't if you like risk
chunk2_t myChunk2 = {p, c};
swap_function(x, cb, &myChunk1);
swap_function(x, cb, &myChunk2);
}
Using function pointer stored in structure:
#define FUNC_ONE_METHOD 1
#define FUNC_TWO_METHOD 2
typedef struct chunk{
double a, b, c;
double p[];
int method;
double (*pfunc) (double x, struct chunk *self);
}chunk_t;
double swap_function(double x, chunk_t *ch){
switch (ch->method)
{
case FUNC_TWO_METHOD:
ch->pfunc = my_func_two;
break;
case FUNC_ONE_METHOD:
ch->pfunc = my_func_one;
break;
default:
return -1; // or throw error
return ch->pfunc(x, ch);
}
chunk c = {.a= 1, .b=3, .c=1, .method=1};
swap_function(x, &c);

Your understanding is true.
The signature of your function-pointer must match the corresponding function(s).
Consider learncpp.com:
Just like it is possible to declare a non-constant pointer to a variable, it’s also possible to >declare a non-constant pointer to a function. The syntax for doing so is one of the ugliest things >you will ever see:
// pFoo is a pointer to a function that takes no arguments and returns an integer
int (*pFoo) ();
The parenthesis around *pFoo are necessary for precedence reasons, as int *pFoo() would be interpreted as a function named pFoo that takes no parameters and returns a pointer to an integer.
In the above snippet, pFoo is a pointer to a function that has no parameters and returns an integer. pFoo can “point” to any function that matches this signature.
...
Note that the signature (parameters and return value) of the function pointer must match the signature of the function.

What you want is possible, but a bit dirty. Function pointers can be cast to one another without losing information. The important thing is that you'd always have to call a function through such a pointer only with a signature that corresponds to its definition. So if you cast back before calling the function(s) and call with the correct arguments, all should be fine.

A sample of Typecasting approach for using a same function pointer for different functions of different prototypes.
<>
#include <stdio.h>
typedef void (*myFuncPtrType) (void);
typedef int (*myFunc2PtrType)(int, int);
typedef int * (*myFunc3PtrType)(int *);
static void myFunc_1 (void);
static int myFunc_2 (int, int);
static int* myFunc_3 (int *);
const myFuncPtrType myFuncPtrA[] = {
(myFuncPtrType)myFunc_1,
(myFuncPtrType)myFunc_2,
(myFuncPtrType)myFunc_3
};
static void myFunc_1 (void)
{
printf("I am in myFunc_1 \n");
}
static int myFunc_2 (int a, int b)
{
printf("I am in myFunc_2\n");
return (a+b);
}
static int* myFunc_3 (int *ptr)
{
printf("I am in myFunc_3\n");
*ptr = ((*ptr) * 2);
return (ptr+1);
}
int main(void) {
// your code goes here
int A[2],C;
int* PTR = A;
(*(myFuncPtrA[0]))();
A[0]=5;
A[1]=6;
C = ((myFunc2PtrType)(*(myFuncPtrA[1])))(A[0],A[1]);
printf("Value of C: %d \n", C);
printf("Value of PTR before myFunc_3: %p \n", PTR);
printf("Value of *PTR before myFunc_3: %d \n", *PTR);
PTR = ((myFunc3PtrType)(*(myFuncPtrA[2])))(&A);
//Lets look how PTR has changed after the myFunc_3 call
printf("Value of PTR after myFunc_3: %p \n", PTR);
printf("Value of *PTR after myFunc_3: %d \n", *PTR);
return 0;
}

Related

How to make a function which receive other function as param (with no known parameters)

Previously I asked How to make a function which receive a function as param in C language. I get an answer Link to the question but this solution is based on the parameters of argument's function. I mean:
int functionToPassAsParameter (int arg1, int arg2){
// do something
}
int functionWhichReceiveFunction (int (*f)(), int arg1, int arg2){
// do something
f(arg1, arg2);
// do something
}
// How to call the function
functionWhichReceiveFunction (&functionToPassAsParameter, 1, 2);
I would like something like:
int functionToPassAsParameter (int arg1, int arg2){
// do something
}
int functionWhichReceiveFunction ( f() ){
// do something
f();
// do something
}
// How to call the function
functionWhichReceiveFunction ( functionToPassAsParameter(arg1, arg2) );
So, when I call the function, I pass the correctly params but when I define the function which receive the other function I do not specify which params I will send to it. Is that possible to make?
EDIT 1:
I wanna achieve pass any function to functionWhichReceiveFunction. Something like:
int function_a (int param1, int param2) { /* Do something */ };
void function_b (char *arg1) { /* Do something */ };
// Call the function with two differents functions regardless return type nor params
int x = functionWhichReceiveFunction ( function_a(param1, param2) );
functionWhichReceiveFunction ( function_b(arg1) );
Define the function to be passed to take a void * as a parameter. That way the function that calls the given function doesn't need to know anything specific about the parameters:
struct params1 {
int arg1;
int arg2;
};
struct params2 {
char *arg1;
char *arg2;
};
int functionToPassAsParameter (void *param){
struct params1 *args = params;
// do something
}
int otherFunctionToPassAsParameter (void *param){
struct params2 *args = params;
// do something
}
int functionWhichReceiveFunction (int (*f)(void *), void *args) {
// do something
f(args);
// do something
}
struct params1 p1 = { 1, 2 };
functionWhichReceiveFunction (&functionToPassAsParameter, &p1);
struct params2 p2 = { "abc", "def" };
functionWhichReceiveFunction (&otherFunctionToPassAsParameter, &p2);
To be able to pass a function with unknown parameters to a function, declare the function that will pass the function as follows:
int g(int (*f)());
The function that is actually passed can have any number of parametes, for example:
int f(int x, void *y);
The call is now as follows:
g(f);
The above means that g passes f, which can have zero or more parameters of any type. This is denoted by the empty parameter list.
A particular function that may need to be passed is for example f.
Now g is called with function f, or any other function.
Note that it is up to g to know which parameters must be passed in calling f. So you need a "protocol" that tells g which function/type is passed. For example, besides passing the function, pass an identifier (int) that says what type of function is passed, for example:
#define fS_I_I 1 // f needs String, int, Int
#define fD_I 2 // f needs Double, Int
#define fI_I 3 // f needs Int, Int
int g(int ID, int (*f)());
g(fI_I, f);
Learn more about closures and tagged unions. Notice that C don't have them. You might want to emulate that with callbacks
I wanna achieve pass any function to functionWhichReceiveFunction
You cannot do that simply and portably. Remember that the signature of a function in C is related to its calling conventions (so to the ABI used by your compiler and your code; for examples, look into Linux x86 ABIs; so floating point arguments could be passed in different registers as integral arguments, so your compiler needs to know the signature of all your function pointers). You need to also give to functionWhichReceiveFunction something which describes the signature.
What you might consider doing, assuming your platform have function pointers of the same size and in the same address space as data pointers (this is very often the case), is to pass to functionWhichReceiveFunction a void* pointer (actually, a function pointer casted to void*) and an enumeration describing it.
For example
enum funsig_en {
funsig_void_to_void,
funsig_int_to_void,
funsig_int_to_double,
funsig_int_double_to_void,
};
Then, you'll have corresponding function signatures (types)
typedef void fun_void_to_void(void);
typedef void fun_int_to_void(int);
typedef double fun_int_to_double(int);
typedef void fun_int_double_to_void(int, double);
Suppose you have these static functions
static void statf_void_to_void(void);
static void statf_int_to_void(int);
static double statf_int_to_double(int);
static void statf_int_double_to_void(int, double);
You might declare
void
functionWhichReceiveFunction (void*res, enum funsig_en sigkind, void*fun, ...);
and you could use it as
functionWhichRecieveFunction(NULL, funsig_void_to_void
(void*)statf_void_to_void);
or
functionWhichRecieveFunction(NULL, funsig_int_to_void,
(void*)statf_int_to_void, 123);
or
double r = 0;
functionWhichRecieveFunction(&r, funsig_int_to_double,
(void*)statf_int_to_double, 2345);
I leave you to code that variadic functionWhichRecieveFunction. You need stdarg(3) facilities. It would include code like
va_args arglist;
va_start (arglist, fun);
switch(sigkind) {
case funsig_int_to_void: {
int a = va_arg(arglis, int);
fun_int_to_void* fptr = (fun_int_to_void*)fun;
(*fptr)(a);
return;
} // end case funsig_int_to_void
much later you'll need some va_end(arglis); near the end of your functionWhichRecieveFunction body.
Another possibility is using varargs. In the following example every function being called does its own interpretation of parameters.
#include <stdio.h>
#include <stdarg.h>
// expects 4 arguments (int, int, int, char*)
void f1(va_list args) {
int a, b, c;
char *d;
a = va_arg(args, int);
b = va_arg(args, int);
c = va_arg(args, int);
d = va_arg(args, char *);
printf("%d, %d, %d: %s\n", a, b, c, d);
}
// expects 3 ars (int, int, char*);
void f2(va_list args) {
int a, b;
char *c;
a = va_arg(args, int);
b = va_arg(args, int);
c = va_arg(args, char *);
printf("%d, %d: %s\n", a, b, c);
}
void caller(void (*f)(va_list), ...) {
va_list args;
va_start(args, f);
f(args);
va_end(args);
}
int main() {
caller(&f1, 0, 1, 3, "hello");
caller(&f2, 1, 2, "bye");
return 0;
}
Another possibility is to have caller to interpret parameters based on some type info and call a correct function call. This might be useful if you have a limited number of argument patterns and just regular functions to call:
void f3(int a, int b, int c, char *d) {
printf("%d, %d, %d: %s\n", a, b, c, d);
}
void f4(int a, int b, char *c) {
printf("%d, %d: %s\n", a, b, c);
}
typedef enum {
type1, type2
} Types;
void caller1(Types t, void (*f)(), ...) {
va_list args;
va_start(args, f);
switch (t) {
case type1: {
int a, b, c;
char *d;
a = va_arg(args, int);
b = va_arg(args, int);
c = va_arg(args, int);
d = va_arg(args, char *);
f(a,b,c,d);
break;
}
case type2: {
int a, b;
char *c;
a = va_arg(args, int);
b = va_arg(args, int);
c = va_arg(args, char *);
f(a,b,c);
}
}
va_end(args);
}
int main() {
caller1(type1, &f3, 3,2,1, "hi");
caller1(type2, &f4, 3,2,"take care");
return 0;
#Paul Ogilvie, this is the code:
int f(int x, void *y) {
return x;
};
int g(int (*f)()) {
int x = f(1, NULL); // call f with parameters
printf("X is: %d", x);
return(x); // return result
};
int main()
{
//g( f(1, 2) ); // this passes the result of a call to f, not f
g( f ); // this passes f
return 0;
}

Structure return type interpretation

When I refer int func(int a,int b), it means we are referring to function that will return integer data. What does the following statement mean:
struct datatype func(int a, int b);
I know the function is going to return a structure type, but how exactly can I interpret it. I mean in case of integer return type, it was returning a whole number, let's say 5; in the second case what kind of data should I expect, since a structure contains mixture of data types sometimes?
For example:
struct datatype
{
int a;
float b;
char array[8];
int *ptr;
};
What type will it return then, because struct contains a mix of many data types?
When a function is declared to return an int, it returns an int.
When a function is declared to return a double *, it returns a double *.
When a function is declared to return a struct datatype, it returns a struct datatype.
Given:
struct datatype
{
int a;
float b;
char array[8];
int *ptr;
};
struct datatype func(int a, int b);
You could write code like this inside another function:
struct datatype rv = func(1, 2);
and now you can use any and all of the elements of rv because the return value was copied into the variable, just the same as you could write:
double dv = sqrt(3.1415926538);
In all these examples, the function returns a value of the type it is declared to return. You can save the return value; you can (but probably shouldn't) ignore it. Within limited contexts, you can use the returned value immediately as an argument to a function, or to assign part of the return value to a variable of an appropriate type. Note that you can't apply the & (address of) operator to the result of a function call; it is not an lvalue.
This code illustrates the options available to you:
#include <stdio.h>
#include <string.h>
struct DataType
{
double d;
int i;
char s[20];
};
static struct DataType function(double a1, int a2, char *a3)
{
struct DataType rv;
rv.d = a1;
rv.i = a2;
strncpy(rv.s, a3, sizeof(rv.s));
rv.s[sizeof(rv.s)-1] = '\0';
return rv;
}
static void printer(struct DataType dt)
{
printf("d = %f; i = %d; s = [%s]\n", dt.d, dt.i, dt.s);
}
int main(void)
{
function(0, 0x0, "");
printer(function(3.14159265358979323844, 0x03C0, "Slice of the pie"));
printf("d = %f\n", function(2.71828182845904523536, 0x2203, "Existential").d);
struct DataType dt = function(1.61803398874989484820, 0x03A6, "Oh fie upon a phi");
printf("d = %f; i = %d; s = [%s]\n", dt.d, dt.i, dt.s);
double d = function(1.41421356237309504880, 0x221A, "I'm rooting for two").d;
printf("d = %f\n", d);
return 0;
}
The output from that is:
d = 3.141593; i = 960; s = [Slice of the pie]
d = 2.718282
d = 1.618034; i = 934; s = [Oh fie upon a phi]
d = 1.414214
A struct is a product type. It contains one value for each of its elements, and each element can have a different type. In memory, it's a bunch of data, one piece per element, lain out in a row (roughly). A union is the opposite. It contains exactly one value of one type, but you don't know exactly which type that is, because there are multiple choices. In memory, it's one area containing one value of ambiguous type.
In your example, func returns an int and a float and a char[8] and an int*.
struct datatype data = func(...);
int int1 = data.a;
float fl = data.b;
char* ch = data.array;
int *int2 = data.ptr;
// Four values and four types in one package
In this example, we have a union:
union datatype
{
int a;
float b;
char array[8];
int *ptr;
};
union datatype func();
Now, func returns an int or a float or a char[8] or an int*, and you decide which one you think it is when you access it.
union datatype data = func();
if(testSomething1())
{
int int1 = data.a; // I think that func gave me an int, so I'll take it out
}
else if(testSomething2())
{
float fl = data.b; // I think func gave me a float in this branch
}
else if(testSomething3())
{
char* ch = data.array; // If testSomething3(), then func() returns a char[8]
}
else
{
int *int2 = data.ptr; // Otherwise, it's an int*
}
// One value with 4 choices of type.
// You can also do evil things like
// union { float f; int i } u;
// u.i = 500;
// something(u.f);
// Which reinterprets an int as a float. Sometimes that makes sense, but most times
// you've done something wrong.
A union is what you'd call something of "mixed type", because the type of an union's value really is ambiguous. A struct, however, is not mixed. It contains multiple, separate pieces of data, and each piece has its own, clear type.

Use case of function pointers in c

One of the common use cases I've come across when I read about function pointers is that they can be used to make a function more flexible, as part of the functionality of the function can be taken in as a parameter. An example for this is qsort where I can make a compare function to decide what is meant by greater and lesser (ascending, descending, is a multiple of,etc) and pass the compare funtion pointer to qsort function.
Here, the function repeat has addptr as parameter and therefore performs multiplication.
int add(int a, int b)
{
return a+b;
}
int (*addptr)(int,int);
int repeat(int a,int b,int (*funcptr)(int,int))
{
int i,ans=0;
for(i=0;i<a;i++)
{
ans=(*funcptr)(ans,b);
}
return ans;
}
int main()
{
addptr=&add;
printf("%d\n",repeat(7,5,addptr));
return 0;
}
But the same exact thing can be done without function pointers at all!
int add(int a, int b)
{
return a+b;
}
int repeat(int a,int b,int func(int,int))
{
int i,ans=0;
for(i=0;i<a;i++)
{
ans=func(ans,b);
}
return ans;
}
int main()
{
printf("%d\n",repeat(7,5,add));
return 0;
}
So why is this even one of the uses of function pointers?
What is the advantage of the first code over the second?
There is a rule C11 6.7.6.3/8 saying that if you write a function inside a parameter list, it will get adjusted to a pointer to function of that type:
A declaration of a parameter as ‘‘function returning type’’ shall be
adjusted to ‘‘pointer to function returning type’’,
This works similar to when you write an array as function parameter, it gets adjusted to a pointer to the first element.
That being said, it is not really meaningful to write a function as a parameter, it is just very confusing to the reader. Use function pointers instead.
EDIT
For maximum readability, I would personally recommend using this style:
typedef int operation_t (int, int);
int repeat (int a, int b, operation_t* operation)
{ ...
Though the most commonly used style is perhaps this one:
typedef int (*operation_t) (int, int);
int repeat (int a, int b, operation_t operation)
{ ...
I prefer the former since hiding pointers behind typedefs is a bad idea, and since that style makes function pointers consistent with regular pointers.
As noticed in comment by #user2390668, func in repeat in already a function pointer. And when you call it, add decays to a function pointer.
If your question is what is a possible use case for a variable holding a function pointer, we must try to imagine a use case where a function will not only be passed as a parameter, but will have to be stored. An example for that would be simulating polymorphism of structs in C. Here is an oversimplified example:
#include <stdio.h>
struct Base {
/* common member variables
...
*/
const char *name;
void (*display)(void *, FILE *fd);
};
struct S1 {
struct Base base;
/* other member variables */
};
void _S1_display(void *this, FILE *fd) {
struct S1 *s1 = this;
fprintf(fd, "In S1, name: %s\n", s1->base.name);
}
struct S2 {
struct Base base;
/* other member variables */
};
void _S2_display(void *this, FILE *fd) {
struct S2 *s2 = this;
fprintf(fd, "In S1, name: %s\n", s2->base.name);
}
void process(void *this, FILE *fd) {
struct Base *base = this; /* valid because base is first element of both S1 and S2 */
base->display(this, fd);
}
int main() {
struct S1 s1 = { "s1", &_S1_display };
struct S2 s2 = { "s2", &_S2_display };
process(&s1, stdout);
process(&s2, stdout);
return 0;
}
Ok, fur such a simply example, polymorphism would not be necessary, but as I said it is oversimplified...
You may use pointers to functions when you need a little more abstraction.
For example, you may want to manage a table of operators that a generic function should use:
int add(int a, int b) {
return a+b;
}
int sub(int a, int b) {
return a-b;
}
int mult(int a, int b) {
return a*b;
}
int div(int a, int b) {
return a/b;
}
void doit(int a,int b,int (*ptr[2])(int,int)) {
printf("%d\n",ptr[0](a,b));
printf("%d\n",ptr[1](a,b));
}
int main() {
int (*ptr[2])(int,int);
printf("additives (1) or multiplicatives (2) ?");
int choice;
scanf("%d",&choice);
switch(choice) {
case 1:
ptr[0] = &add;
ptr[1] = ⊂
break;
default:
ptr[0] = &mult;
ptr[1] = &div;
break;
}
doit(7,5,ptr);
return 0;
}
Of course you can also design a doit function with two pointers but sometimes a table is more convenient (think about a variable length table of function pointers for example, I know even in this case we may use a variable arguments list...).
At least, passing a function pointer in parameter is defining a function pointer variable...
Another example is also implementing in C object oriented programming, where you may implement methods as function pointers members.

How to create a typedef for function pointers

I think it would be easier to use function pointers if I created a typedef for a function pointer, but I seem to be getting myself tripped up on some syntax or usage or something about typedef for function pointers, and I could use some help.
I've got
int foo(int i){ return i + 1;}
typedef <???> g;
int hvar;
hvar = g(3)
That's basically what I'm trying to accomplish I'm a rather new C programmer and this is throwing me too much. What replaces <???> ?
Your question isn't clear, but I think you might want something like this:
int foo(int i){ return i + 1;}
typedef int (*g)(int); // Declare typedef
g func = &foo; // Define function-pointer variable, and initialise
int hvar = func(3); // Call function through pointer
You are right. The function pointer can be conveniently used to point to the different functions of the same return type and taking same number of arguments.
The argument types should match the declaration of the function pointer arguments.
In your case you could define your function pointer g as:
typedef int (*g)(int); // typedef of the function pointer.
g is a function pointer for the function returning int value and taking one int argument.
The usage of function pointer could be illustrated by a simple program below:
#include<stdio.h>
typedef int (*pointer_to_function)(int first_parameter_of_type_int, int second_parameter_of_type_int);
int my_function_returning_int_and_taking_two_int_arguments(int par1, int par2)
{
int result = par1 + par2;
return result;
}
int my_mul_function(int par1, int par2)
{
int result = par1 * par2;
return result;
}
int main()
{
int res; // returning result will be here
pointer_to_function my_fun_pointer; // declare function pointer variable;
my_fun_pointer = my_function_returning_int_and_taking_two_int_arguments; // function pointer points to `my_function_returning_int_and_taking_two_int_arguments` function
res = my_fun_pointer(2,3); // Call function through pointer
printf(" result of `my_function_returning_int_and_taking_two_int_arguments` = %d \n", res);
my_fun_pointer = my_mul_function; // now function pointer points to another function: `my_mul_function`
res = my_fun_pointer(2,3); // Call function through pointer
printf(" result of `my_mul_function` = %d \n", res);
return 0;
}
OUTPUT:
result of `my_function_returning_int_and_taking_two_int_arguments` = 5
result of `my_mul_function` = 6
The original way of writing the function returning function pointer is
int (* call(void) ) (int,int);
Here call is a function which takes nothing but returns a function pointer which takes 2 arguments and returns an integer value. Pay attention to the brackets, they are absolutely necessary.
Here is the code:
#include<stdio.h>
int sum(int a,int b) //sum is the function returned by call
{
return a+b;
}
int (*call(void) ) (int ,int);
int main() {
int (*p)(int,int); // way to declare a function pointer
p=call();
printf("%d\n",(*p)(8,3));
}
int( *call(void) )(int,int) {
return sum;
}

Passing addresses to functions in C

I'm new to C and I have a function that calculates a few variables. But for now let's simplify things. What I want is to have a function that "returns" multiple variables. Though as I understand it, you can only return one variable in C. So I was told you can pass the address of a variable and do it that way. This is how far I got and I was wondering I could have a hand. I'm getting a fair bit of errors regarding C90 forbidden stuff etc. I'm almost positive it's my syntax.
Say this is my main function:
void func(int*, int*);
int main()
{
int x, y;
func(&x, &y);
printf("Value of x is: %d\n", x);
printf("Value of y is: %d\n", y);
return 0;
}
void func(int* x, int* y)
{
x = 5;
y = 5;
}
This is essentially the structure that I'm working with. Could anyone give me a hand here?
You should use *variable to refer to what a pointer points to:
*x = 5;
*y = 5;
What you are currently doing is to set the pointer to address 5. You may get away with crappy old compilers, but a good compiler will detect a type mismatch in assigning an int to an int* variable and will not let you do it without an explicit cast.
void function(int *x, int* y) {
*x = 5;
*y = 5;
}
would change the values of the parameters.
In addition to the changes that the other posters have suggested for your function body, change your prototype to void func(int *,int *), and change your function definition (beneath main) to reflect void as well. When you don't specify a return type, the compiler thinks you are trying to imply an int return.
You can't forward declare func(int,int) when in reality it is func(int*, int*). Moreover, what should the return type of func be? Since it doesn't use return, I'd suggest using void func(int*, int*).
You can return a single variable of a struct type.
#include <stdio.h>
#include <string.h>
struct Multi {
int anint;
double adouble;
char astring[200];
};
struct Multi fxfoo(int parm) {
struct Multi retval = {0};
if (parm != 0) {
retval.anint = parm;
retval.adouble = parm;
retval.astring[0] = parm;
}
return retval;
}
int main(void) {
struct Multi xx;
if (fxfoo(0).adouble <= 0) printf("ok\n");
xx = fxfoo(42);
if (strcmp(xx.astring, "\x2a") == 0) printf("ok\n");
return 0;
}

Resources