0

This pointer based question how works?

#include <stdio.h> int main() { double *ptr = (double*)100; ptr=ptr+2; printf("%ld",ptr); return 0; } How answer is calculated 116?

29th Feb 2020, 1:49 PM
Mansa Saxsena
Mansa Saxsena - avatar
5 ответов
0
A pointer holds address of some variable (or some memory location). In your code your assign the explicit address (100) to the pointer. Then you increase it by 16 bytes, because 2 * sizeof(double) = 2 * 8 = 16. value of the pointer = 100 + 16 = 116. Then you print its value as long int, which is 116.
29th Feb 2020, 2:11 PM
andriy kan
andriy kan - avatar
+ 1
Step by step the program does this: 1. Store 100 in ptr 2. Increment ptr by 2 elements. It uses pointer arithmetic here. Notice that ptr is a double precision float pointer. Double is an 8-byte data type. So ptr increments by 8*2 and the result is 100+16 = 116. 3. Print the value held in ptr. This program never does anything with the contents of memory that ptr is pointing to (memory location 100). It is strictly demonstrating pointer math. You can learn more about that in the C course here in SoloLearn. https://www.sololearn.com/Course/C/?ref=app
29th Feb 2020, 2:15 PM
Brian
Brian - avatar
+ 1
I recommend trying it in the coding playground so you can see how it behaves.
29th Feb 2020, 2:31 PM
Brian
Brian - avatar
0
Thanks.Brian andriy kan And if we didn't do explicit type conversions in 2nd line than does it gives any warning or error
29th Feb 2020, 2:25 PM
Mansa Saxsena
Mansa Saxsena - avatar
0
@Mansa Saxsena. Yes. Without type casting a compiler will give warning or error (in C++ it will be an error, in C it may be warning)
29th Feb 2020, 2:31 PM
andriy kan
andriy kan - avatar