0
#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.

9
  • 4
    i's value get changed here for(i=0;i<10;i++) Commented Sep 13, 2015 at 8:15
  • 3
    u is pointing at i, and i is your loop variable, so you're just printing each successive value of i in the loop. Commented Sep 13, 2015 at 8:16
  • 1
    @FelixPalmen no, instead this question should be closed. Commented Sep 13, 2015 at 8:49
  • 1
    @FelixPalmen it absolutely is; Stack Overflow is not a language tutorial site. Basic language features are not to be expected to be taught here (there are Google, and also universities for that which impose expensive tuition fees!). The question also fits a couple of default closure reasons well; for example, the "problem cannot be reproduced" one (which I chose, by the way). Since there's no problem or unexpected behavior, there's nothing to reproduce or ask about. Commented Sep 13, 2015 at 8:54
  • 2
    @FelixPalmen Indeed, ~80% of questions on SO may well be trivially-answerable by either RTFM or just by applying common sense and should in fact be closed IMO. Commented Sep 13, 2015 at 8:56

1 Answer 1

2

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
 }
Sign up to request clarification or add additional context in comments.

4 Comments

nitpick: not in the value of u but in the value of *u .. u will stay constant, being just the address of i. Also suggest to use backticks for variable names in your text for better readability.
I am referring to *u when i said value of u.
Well, the value of u is still the address of i. It's better to be -- super precise here, because obviously the OP didn't understand pointers fully so far.
Please also change the last comment to something like "prints the value to which u points: i" because the value of u is something like 0x777ff....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.