+ 1
Pointer question
Can somebody please explain the third line of this code. It came from the challenges. Also, when and why would you use these lines of code? Thanks int a = 320; char *ptr; ptr = (char*)&a; printf ("%d", *ptr);
7 Respuestas
+ 3
Yes, it seems to depend on how an integer is represented internally, according to the top answer to a somewhat similar problem on Stack Overflow:
https://stackoverflow.com/questions/17260527/what-are-the-rules-for-casting-pointers-in-c
Definitely worth a read in correlation with this problem in my opinion.
+ 1
There's an explicit pointer type casting in the third line. I'm actually surprised that it works even without it. Are there any consequences of not doing it explicitly?
Robin Rademaker it actually prints 64, because the pointer is of the char type (1 byte), while the a variable is an int (4 bytes)
+ 1
{ 𝄋 ℒ 𝄋 } thank you for correcting me 😀👌
0
int a = 320;
char *ptr; // this is your pointer variable
ptr = (char*)&a; // this is the same variable pointing to the adres of a using &
printf ("%d", *ptr); // this prints out
0
I wrote some code about pointers to explain, it is in c++ but the idea is the same
https://code.sololearn.com/c52bQWuV07rY/?ref=app
0
🤔 Strange that it prints out 64 then and not 80 (320/4)
0
Robin Rademaker It must depend on the bytes arrangement in the memory, I guess it may be different on some systems.