Home > OS >  How does sending an argument that's casted to a pointer to a function that accepts pointer work
How does sending an argument that's casted to a pointer to a function that accepts pointer work

Time:11-07

I understand the way print1 function works, but how come when calling print2 function I don't need to pass the address of the argument but rather I just need to cast it to void pointer? I don't understand how the output is correct. What does it mean when I say (void*)20? And then what does the whole "int n = (int)param inside the print2 function does?

#include <stdio.h>
#include <stdlib.h>

void print1(void* param)
{
    int n = *((int*)param);
    printf("You sent: %d\n", n);
}

void print2(void* param)
{
    int n = (int)param;
    printf("You sent: %d\n", n);
}

int main()
{
    int number = 10;
    print1(&number);

    print2((void*)20);

    return 0;
}

CodePudding user response:

(void *)20 converts 20 to a pointer. Per C 2018 6.3.2.3 5, the result is implementation-defined.

print2((void*)20); sends that pointer to print2.

In print2, int n = (int)param; converts that pointer back to int. Per C 2018 6.3.2.3 6, the result is implementation-defined. A common result is that the original integer is restored, provided it has not run afoul of limitations or complications in the addressing mechanism used in the C implementation.

printf("You sent: %d\n", n); sends this restored int to printf.

  • Related