tags:

views:

255

answers:

5

Can anyone explain what I'm doing wrong here to not get 11 as my output?

void foo {
    int *n = malloc(sizeof(int)); 
    *n = 10; 
    n++;
    printf("%d", *n)
}
+9  A: 

If we call the malloc'ed variable x, then your program does this:

                                      n     x
int *n = malloc(sizeof(int));        &x     ?
*n = 10;                             &x    10
n++;                                &x+1   10

You want to do this:

                                      n     x
int *n = malloc(sizeof(int));        &x     ?
*n = 10;                             &x    10
(*n)++;                              &x    11
Artelius
`++` has higher precedence than the unary `*`, so parentheses are needed in order to perform the dereference before the increment.
James McNellis
dmckee
Of course it is. Edit reflects this.
Artelius
@dmckee: The postfix `++` has higher precedence than both the prefix `++` and unary `*` (the prefix `++` and unary `*` have the same precedence, as you say).
James McNellis
+1 for the nice illustration
Matt Curtis
@James: Conceded, but it's not it the text, I had to go tothe appendix to find it.
dmckee
James McNellis
+25  A: 

n++ increments the pointer n, not the integer pointed to by n. To increment the integer, you need to dereference the pointer and then increment the result of that:

(*n)++;
James McNellis
Suggest you change the wording slightly: "To dereference the integer" -> "To increment the integer"
Matt Curtis
@Matt: Yes; I just saw that. There must have been a bus error between my brain and fingers. :-) Thanks.
James McNellis
+2  A: 

You set n[0] to 10, and then you print n[1]. malloc() does not initialize the memory that it gives you, so what gets printed is unpredictable - it's whatever garbage happened to be in n[1].

rettops
Except, of course, that there is no `n[1]`, so you are reading from beyond the end of the allocated memory, the behavior of which is undefined.
James McNellis
Absolutely right! I hadn't noticed that he used malloc to allocate a single int.
rettops
+2  A: 

You can get 11 as your output with this code:

void foo {
    int *n = malloc(sizeof(int)); 
    *n = 10; 
    (*n)++; 
    printf("%d", *n)
}
Ikbear
+1  A: 

n++ moves the pointer sizeof(int) bytes forward.

Jason
yes...I realized and edited :)
Jason