Home > Back-end >  How to cast and pass the address of a variable to a function in C
How to cast and pass the address of a variable to a function in C

Time:03-26

Let's imagine that I have a variable of type int which I would like to pass to a C function as a parameter. This function expects that the parameter is a pointer of type long long. Is it possible to cast this variable and then pass its address to the function like this and without using additional variables in the program:

int val;

val = 10;

my_function((long long) &val);



void my_function(long long *parameter)
{
     // do some operations with 'parameter'
}

Not sure if this code has hidden effects.

CodePudding user response:

No. You must pass the correct pointer type.

long long is 8 bytes (probably), int is 4 bytes (probably) and if you try to pretend an int is a long long, when the code actually uses the pointer it will access the int plus another 4 bytes next to it, which will screw things up.

You must actually use a long long variable:

long long llval = val;
my_function(&llval);
val = llval; // if needed

CodePudding user response:

The cast operator yields the value of the casted scalar object. You may not take the address of the value. You need to introduce an intermediate variable as for example

int val;

val = 10;

long long tmp = val;
my_function( &tmp );

But if you are trying to do that then it seems the design of your program has drawbacks. For example why is not the variable val initially declared as having the type long long? The function declaration means that it accepts objects by reference and the passed objects will be changed within the function because the parameter is declared without the qualifier const. So either you have to declare the variable val as having the type long long or to introduce another function that will accept objects of the type int by reference.

CodePudding user response:

Normal Case

In a normal case, my_function does something with a long long that parameter points to. Then there must be a long long that parameter points to. You must provide to the function either a long long (or an object that is permitted by the aliasing rules in C 2018 6.5 7) or at least the memory space where the function can create one.

There is a way to do this without creating an additional variable; you can use a compound literal to create a long long in the function call:

my_function(& (long long) {val});

However, you will not be able to use the value of that long long after the function returns. Any changes the function makes to the long long will not affect val.

Abnormal Case

If my_function does not use parameter as a pointer to long long, in spite of its declared type, then you can pass it some other pointer that has been converted to a long long. There are such uses permitted by the C standard, but this would generally be inappropriate code to write, and what pointers you can pass would depend on what my_function is doing.

  • Related