+ 2
How do we read it: *((int *)ptr) ?
C Pointer
13 Réponses
+ 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)
+ 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.)
+ 6
~ swim ~ Look at the code OP posted...
+ 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;
}
+ 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.
+ 2
Ok all, thanks a lot. I could figure out it now.
+ 2
+ 1
My brain get an error here: *((int *)ptr)
+ 1
What is the problem? It's okay!
+ 1
*AsterisK* : just try to search at: https://www.ioccc.org, i think it is from.
0
*(int*) p
Explain