Passing addresses to functions in C - 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;
}

Related

How to pass structure field name to function?

I have many similar function calls dealing with one structure, but each call is using different field of structure.
Example:
typedef struct {
int i1;
int i2;
int i3;
} S;
functions to get structure fields (it would be better to avoid them):
int getFieldI1 (S *s){ return s->i1; }
int getFieldI2 (S *s){ return s->i2; }
int getFieldI3 (S *s){ return s->i3; }
function i have to call many times:
void doJob (int (*get_field_func)(S *)){
//some code
S s;
int v = get_field_func(&s);
//some code
}
i call doJob() this way:
doJob(&getFieldI1);
doJob(&getFieldI2);
doJob(&getFieldI3);
i would like to do like this:
doJob(i1);
doJob(i2);
doJob(i3);
is it possible in C?
option 1 - offsets
You can use memory offsets.
void doJob (int offset){
//some code
S s;
int v = *(&s+offset*sizeof(int));
//some code
}
You can call it like this:
doJob(0);//i1
doJob(1);//i2
doJob(2);//i3
As pointed out in the comments, the offsets are unsafe. You can create a check for this:
if(offset>2||offset<0){
//some kind of error
}
Also, this can only be used if the structure only contains integers(or elements of the same type, you would need to adjust it)(see comments).
If there are elements before s1, s2 and s3, you'll need to add the size of the elements(as padding, just add it);
option 2 - constants
Another option (that hasn't the mentioned problems) is to define constants/macros:
You'll just define them like this:
#define I1 &getFieldI1
#define I2 &getFieldI2
#define I3 &getFieldI3
and just call it using:
doJob(I1);
doJob(I2);
doJob(I3);
Just pass in a pointer to the field:
void doJob( int* fieldPointer )
{
assert( fieldPointer != NULL );
// Get the field value:
int v = *fieldPointer;
// Do something with the field value:
v += 10;
// Save the updated value back to the field:
*fieldPointer = v;
}
Usage:
S structInstance = ...
doJob( &structInstance.i1 );
doJob( &structInstance.i2 );
doJob( &structInstance.i3 );
How to pass structure field name to function?
In general, you cannot. A typical library coded in C does not show fields of internal struct to outside. In other words, a field name is only known to the compiler, and relevant to the current translation unit, and makes no sense at runtime.
Consider the following metaprogramming approach: write a metaprogram (in C or in some scripting language like Guile, awk, Python, etc...) generating your C code, and set up your build accordingly. That might mean to edit your Makefile, or configure your build automation tool.
This is usual practice since the previous century. Look into SWIG or RPCGEN as a famous example.
You might perhaps use preprocessor tricks, e.g. X-macros.
Unfortunately, C doesn't allow exactly what you need. But you can achieve a partial win with some code changes.
I have one and half solutions. For the first I propose a (simplified!) implementation, for the second I provide just an hint. Please, check if they can be acceptable for you.
Your example structure:
typedef struct {
int i1;
int i2;
int i3;
} S;
I would define an enum representing the specific field:
typedef enum
{
FIELD_ID_I1,
FIELD_ID_I2,
FIELD_ID_I3,
FIELD_ID_MAX
} FieldId_e;
Then I would add a field parameter in your general function, managing internally the correct field to be returned. Some smart error managing in case of wrong ID has to be done here. I just return -1 for brevity.
int getField (S *s, FieldId id)
{
int ret = -1;
switch(id)
{
case FIELD_ID_I1:
ret = s->i1;
break;
case FIELD_ID_I2:
ret = s->i2;
break;
case FIELD_ID_I3:
ret = s->i3;
break;
}
return ret;
}
Your doJob will become
void doJob (int (*get_field_func)(S *, FieldId), FieldId id){
//some code
S s;
int v = get_field_func(&s, id);
//some code
}
And final call will become this one. But probably (and it depends on your scenario) having a single general function will make possible to omit the function pointer, simplifying much the interface.
doJob(&getField, FIELD_ID_I1);
doJob(&getField, FIELD_ID_I2);
doJob(&getField, FIELD_ID_I3);
Just a short reference to another tricky solution that would require to play with pointers.
Do you know offsetof macro? (Wikipedia EN)
It evaluates to the offset (in bytes) of a given member within a
struct or union type, an expression of type size_t. The offsetof()
macro takes two parameters, the first being a structure name, and the
second being the name of a member within the structure.
In this case you could have something like
int getField (S *s, size_t offset);
doJob(&getField, offsetof(S, i1));
I failed to guess right types for i1/i2/i3, sorry. So I use auto keyword from c++:
#include <stdio.h>
typedef struct {
int i1;
int i2;
int i3;
} S;
int getFieldI1 (S *s){ return s->i1; }
int getFieldI2 (S *s){ return s->i2; }
int getFieldI3 (S *s){ return s->i3; }
void doJob (int (*get_field_func)(S *)){
//some code
S s = {1,2,3};
//S s;
int v = get_field_func(&s);
//some code
printf("got: %d\n", v);
}
int main() {
S s = {1,2,3};
auto i1 = getFieldI1;
auto i2 = getFieldI2;
auto i3 = getFieldI3;
doJob(i1);
doJob(i2);
doJob(i3);
}
Then
g++ 59503102.cxx -o 59503102 && ./59503102
as expected produces
got: 1
got: 2
got: 3
plain c version
#include <stdio.h>
typedef struct {
int i1;
int i2;
int i3;
} S;
int getFieldI1 (S *s){ return s->i1; }
int getFieldI2 (S *s){ return s->i2; }
int getFieldI3 (S *s){ return s->i3; }
void doJob (int (*get_field_func)(S *)){
//some code
S s = {1,2,3};
//S s;
int v = get_field_func(&s);
//some code
printf("got: %d\n", v);
}
int main() {
S s = {1,2,3};
int (*i1)(S *) = getFieldI1;
int (*i2)(S *) = getFieldI2;
int (*i3)(S *) = getFieldI3;
doJob(i1);
doJob(i2);
doJob(i3);
}

Why do we need pointer to a structure pointer to change members value?

While for simple types (simple types: int, char..) we directly use pointers (their address) as an argument to a function to permanently change their value in the main program, can someone explain to me why for structures we need a pointer to a Structure pointer, and not just a pointer?
struct someStruct
{
int field1;
int field2;
}
void initializeFields(struct someStruct** foo)
{
//changing fields
}
//while
void initializeFields(struct someStruct* foo) //does not work ?
struct someStruct* foo is fine, you don't need struct someStruct** foo. Not sure where you got that idea from, but it's not correct.
To only change the members of the structure you don't need that. But to change the actual pointer to the structure you need to emulate pass by reference by using pointer to a pointer to the structure.
For example, to only change a member this is enough
void initializeFields(struct someStruct* foo)
{
foo->field1 = 1;
foo->field2 = 2;
}
int main(void)
{
struct someStruct bar;
initializeFields(&bar);
printf("field1 = %d\n", bar.field1);
printf("field2 = %d\n", bar.field2);
return 0;
}
But if you for example want to dynamically allocate the structure in the function you need to emulate pass by reference:
void initializeFields(struct someStruct** foo)
{
// The difference is this assignment
*foo = malloc(sizeof(struct someStruct));
(*foo)->field1 = 1;
(*foo)->field2 = 2;
}
int main(void)
{
struct someStruct* bar;
initializeFields(&bar);
printf("field1 = %d\n", bar->field1);
printf("field2 = %d\n", bar->field2);
return 0;
}
Two more examples to show the difference between pass by value and emulating pass by reference.
Consider the following program:
#include <stdio.h>
void foo(int y)
{
y = 5;
}
int main(void)
{
int x = 1;
printf("1: x = %d\n", x);
foo(x);
printf("2: x = %d\n", x);
return 0;
}
The above program will print
1: x = 1
2: x = 1
That is because a copy of the value in x is passed to the function foo. Modifying the local copy inside foo will not modify the original variable x inside main.
Now to emulate pass by reference:
#include <stdio.h>
void foo(int *y)
{
*y = 5;
}
int main(void)
{
int x = 1;
printf("1: x = %d\n", x);
foo(&x);
printf("2: x = %d\n", x);
return 0;
}
This program will print
1: x = 1
2: x = 5
This is because we don't change the pointer variable y inside the function foo, but we change the value of where it points, which happens to be the variable x in the main function.
There are very specific cases where you need pointer to a struct pointer (array of struct pointers, mostly).
Otherwise, a pointer to a struct is enough.
struct someStruct
{
int field1;
int field2;
}
void initializeFields(struct someStruct* foo)
{
foo->field1 = 42;
foo->field2 = -1;
}

Printing an int in C

I am trying to print an int a before and after calling a set function to set the value of a. I am doing this in C. When I compile it I have no errors but when I attempt to run it, I get a segmentation fault.
Here is what I have so far:
#include <stdio.h>
int main(){
int* a;
printf("%d",*a);
set(10);
printf("%d", *a);
return 0;
}
int set(int*a, int val){
*a = val;
return *a;
}
int main(){
int* a;
printf("%d",*a);
What you have there is a pointer to an int rather than an actual int.
And, while that's the correct way to print the int it points to, unfortunately it points to an arbitrary memory location which is why you're crashing.
You are not allowed to dereference arbitrary pointers, they have to point to something valid, such as if you begin your code with:
int main(){
int target_of_a = 42;
int *a = &target_of_a;
printf ("%d", *a);
In addition, you probably should be calling set with something like:
set (a, 10);
something the compiler would generally warn you about though, in this case, it would probably just say it didn't know about set at the time you called it. If it had known, it could have told you about the parameter mismatch.
One way for you to acheive that is to ensure you have a prototype defined for the function before you call it:
int set(int*,int);
or just move the function to before main. With all those changes (and a bit of a general tidy up), you'd end up with:
#include <stdio.h>
int set (int *a, int val) {
*a = val;
return *a;
}
int main (void) {
int target_of_a = 42;
int *a = &target_of_a;
printf ("%d\n", *a);
set (a, 10);
printf ("%d\n", *a);
return 0;
}
The wisdom of returning the variable you're changing is also debatable but there are situations where that might be useful (such as if you want to us it immediately without another statement: printf ("%d\n", set (a, 10)); for example) so I've left that as is.
I should also mention that it's a little unusual to artificially create a pointer variable in a situation like this.
Now it may be that your code is just a simplification of some more complex scenario where you already have a pointer but, if not, the usual way to do this would be to just have the int itself and just use & to create one on the fly:
#include <stdio.h>
int set (int *a, int val) {
*a = val;
return *a;
}
int main (void) {
int a = 42;
printf ("%d\n", a);
set (&a, 10);
printf ("%d\n", a);
return 0;
}
This code should work:
#include <stdio.h>
#define FIRST_VALUE 20
#define SECOND_VALUE 10
int main(){
int a = FIRST_VALUE; /* Declare a as an int variable. */
printf("Before set: a = %d\n",a); /* Print the first value. */
set(&a, SECOND_VALUE); /* Pass the ADDRESS of a to set. */
printf("After set: a = %d\n", a); /* Print the new value of a. */
return 0;
}
int set(int*a, int val){
*a = val;
return *a;
}
Note that the variable a in main() is not the same as the variable a in set(); you have to pass a pointer to a to set() in order for set() to operate on it.
Try this:
And remember, all functions before the main() (if you're using only one file)
Take a read on value and reference params.
#include <stdio.h>
int set(int* a, int val){
*a = val;
}
int main(){
int a = 2;
printf("%d\n", a);
set(&a, 10);
printf("%d\n", a);
return 0;
}

Function pointer to different functions with different arguments in 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;
}

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;
}

Resources