+ 1

In void pointr in c, why there is a '*' after 'int' ?

printf("void ptr points to %d\n",*((int *)ptr));

30th Dec 2022, 2:47 AM
S M Rakibul Alam
S M Rakibul Alam - avatar
3 ответов
+ 4
A void pointer is a pointer to some data with no type attached. We are basically saying to the compiler "this pointer points to 'some' data, but I only care about the memory location of the data, nothing else". So to access a void pointer, you need to 'cast' it to a pointer of some data type. In the code above (int*)ptr casts 'ptr' to a 'int pointer'. Now we can dereference (*) it to get the int stored in memory pointed by 'ptr' *((int*)ptr) It's basically doing *ptr but after casting ptr to an int pointer, hence *((int*)ptr)
30th Dec 2022, 6:46 AM
XXX
XXX - avatar
0
Dmitry Could you expand on the line "(-46864457) which, as an address, does not exist at all, since the address is read as a hexadecimal number, and not as an integer." ? What do mean by "the address is read as a hexadecimal number, and not as an integer"? I mean, hexadecimal numbers are.... integers right? Pointers are displayed in hexadecimal format, but they are numbers. You are right that the address (-46864457) doesn't exist, but that's because you are casting a pointer to a signed int. Try casting a pointer to (unsigned long) and printing it, that will give you the same number in decimal format as you would get by printing it as a pointer
30th Dec 2022, 8:30 AM
XXX
XXX - avatar