Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferencing void pointer

I was reading a guide to threads programming using pthreads.h library when i encountered this kind of code. Not exactly this, but the thing is in void * pointer dereferencing.

#include <stdio.h>

void func(void * x) {
    printf("%d\n", (int) x);
}

int main() {
    int x = 10;
    func((void *) x);
    return 0;
}

Why i can just use

(int) x

for dereferncing void * pointer in func?

I thought it has to be something like this:

* ((int *) x)

Similar question about this line of code in main function:

func((void *) x);

I don't even get address of x variable here.

like image 542
Joey74 Avatar asked Dec 06 '25 02:12

Joey74


2 Answers

You're not dereferencing x when doing (int) x. You just convert a pointer (which is more or less an address) to an int, which is a number representation, which might be printed.

EDIT: By the way, converting x to an signed integer (int) should give you a compiler warning. The more proper way to deal with this is

printf("%p\n", x);

%p is a special format specifier, which interprets the thing handed to printf as a pointer (address specifier), printing it in hex, which is often more useful when dealing with addresses.

EDIT2: By the way, too, to dereference x, you'd first have to give it a meaningful pointer type:

char a = *((char*)x); 

will set a to the character that is stored at the address that p contains.

like image 177
Marcus Müller Avatar answered Dec 08 '25 18:12

Marcus Müller


The function func just prints the address of pointer x.

If you want to see func in action, do this:

void func(void * x) {
    printf("%d\n", (int) x);
}

int main() {
    for (int i = 0; i < 5; i++) {
        void *x = malloc(100);
        func(x);
        free(x);
    }
}

This code will allocate 5 memory blocks, and print their addresses.

like image 28
Krzysztof Kozielczyk Avatar answered Dec 08 '25 16:12

Krzysztof Kozielczyk