Radhika Singh
Radhika Singh

Reputation: 27

Unexpected output when printing the value of a variable using a pointer

#include <stdio.h>
int main()
{
    int i = 5;
    int* u = &i;
    printf("%d\n", *(u + 0));
    for(i = 0; i < 10; i++)
        printf("%d\n", *u);
}

Output is:

5
0
1
2
3
4
5
6
7
8
9

But I think it should print 5 11 times.

Upvotes: 0

Views: 53

Answers (1)

Sourav Kanta
Sourav Kanta

Reputation: 2757

As u contains the address of the variable i any changes to i will be reflected in the value of *u . So going through the code :

#include <stdio.h>
int main()
{
    int i = 5;
    int* u = &i;    //u contains the address of i so change in i changes *u
    printf("%d\n", *(u + 0));    //prints the value of i as *u is the value i that is 5
    for(i = 0; i < 10; i++)    //the value of i changes so does *u.Therefore *u is incremented from 0 to 9 1 at a time.
    printf("%d\n", *u);     //prints the value of *u whch is effectively i
 }

Upvotes: 2

Related Questions