+ 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);

19th Apr 2019, 5:34 PM
Heather
Heather - avatar
7 Respostas
+ 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.
19th Apr 2019, 9:45 PM
Shadow
Shadow - avatar
+ 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)
19th Apr 2019, 8:21 PM
{ 𝄋 ℒ 𝄋 }
{ 𝄋 ℒ 𝄋 } - avatar
+ 1
{ 𝄋 ℒ 𝄋 } thank you for correcting me 😀👌
19th Apr 2019, 8:39 PM
Robin R.
Robin R. - avatar
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
19th Apr 2019, 8:11 PM
Robin R.
Robin R. - avatar
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
19th Apr 2019, 8:13 PM
Robin R.
Robin R. - avatar
0
đŸ€” Strange that it prints out 64 then and not 80 (320/4)
19th Apr 2019, 8:51 PM
Robin R.
Robin R. - avatar
0
Robin Rademaker It must depend on the bytes arrangement in the memory, I guess it may be different on some systems.
19th Apr 2019, 8:54 PM
{ 𝄋 ℒ 𝄋 }
{ 𝄋 ℒ 𝄋 } - avatar