Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can someone explain the output of this program written in C

int x = 5;

int *p = &x;

printf("%u\t%u\n",&x,p);

printf("%d\n",*(p++));

printf("%d\n",*p);

Can someone help me understand the pointer arithmetic?
And what will be the output?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

After you increased ptr, it’s no longer pointing anywhere valid. Dereferencing the pointer with *ptr leads to undefined behavior.

It might be simpler to understand if you consider &x to be an array of a single element, and the initialization of p (or ptr, whichever you really picked) makes p point to the first (and only) element of that array. By increasing p it will be pointing out of bounds of that single-element array.


To visualize it, lets draw it out…

First you have

int x = 5;

which can be drawn as

+-------+
| x (5) |
+-------+

Now we define and initialize the pointer to that:

int *p = &x;

So now it will look like this:

+-------+
| x (5) |
+-------+
 ^
 |
+---+
| p |
+---+

The variable p is pointing to the variable x (the "up-arrow" in the illustration above).

If you then increase the pointer:

p++;

then it will look like this:

+-------+----
| x (5) | ???
+-------+----
         ^
         |
        +---+
        | p |
        +---+

The pointer is no longer pointing to x. What it points to is unknown, and the value at that location is also unknown.

So to answer the question about what is printed and why, we can’t say.

Undefined behavior (UB for short) often isn’t predicable, and there might be no way to tell what will happen.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading