Search code examples
ccastingpass-by-referencefunction-calladdress-operator

How to cast and pass the address of a variable to a function in C


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.


Solution

  • 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