+ 2

How do we read it: *((int *)ptr) ?

C Pointer

16th Feb 2019, 6:52 AM
HD Satria
HD Satria - avatar
13 ответов
+ 8
A void pointer points to a memory location but doesn't contain any information about the type of data it points to. So it doesn't know if the memory location it points to is an integer, a character, a float or whatever. *ptr dereferences the pointer (=gets the value at the memory location the pointer points to). (int*) tells the compiler to handle the value as an integer (type casting from a void pointer to an int pointer)
16th Feb 2019, 7:28 AM
Anna
Anna - avatar
+ 7
ptr is a void pointer, so a pointer that hasn't specified which type it points to. Before you access it you need to cast it into a type, just like sometimes you convert a string to an int (int *) ptr // roughly like (int)some_char And to access what the pointer points to, you need the star as always, so *((int *)ptr). (btw: You don't need the outer set of parentheses.)
16th Feb 2019, 7:26 AM
HonFu
HonFu - avatar
+ 6
~ swim ~ Look at the code OP posted...
25th Feb 2019, 5:49 AM
Anna
Anna - avatar
+ 3
#include <stdio.h> int main() { int x = 33; float y = 12.4; char c = 'a'; void *ptr; ptr = &x; printf("void ptr points to %d\n", *((int *)ptr)); ptr = &y; printf("void ptr points to %f\n", *((float *)ptr)); ptr = &c; printf("void ptr points to %c", *((char *)ptr)); return 0; }
16th Feb 2019, 7:08 AM
HD Satria
HD Satria - avatar
+ 2
ptr is a variable of type *int. ptr is a pointer too. So ptr points to a pointer pointing to an integer I guess. Correct me if I am wrong.
16th Feb 2019, 7:02 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 2
Ok all, thanks a lot. I could figure out it now.
16th Feb 2019, 8:15 AM
HD Satria
HD Satria - avatar
16th Feb 2019, 7:49 PM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 1
My brain get an error here: *((int *)ptr)
16th Feb 2019, 7:09 AM
HD Satria
HD Satria - avatar
+ 1
What is the problem? It's okay!
16th Feb 2019, 7:20 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 1
*AsterisK* : just try to search at: https://www.ioccc.org, i think it is from.
17th Feb 2019, 12:21 AM
HD Satria
HD Satria - avatar
0
*(int*) p Explain
17th Apr 2023, 2:39 PM
suthan A
suthan A - avatar