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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With