Why is the integer not incremented in this code?
Can anyone explain what I'm doing wrong here to not get 11开发者_JAVA技巧 as my output?
void foo {
int *n = malloc(sizeof(int));
*n = 10;
n++;
printf("%d", *n)
}
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)++;
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
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].
You can get 11 as your output with this code:
void foo {
int *n = malloc(sizeof(int));
*n = 10;
(*n)++;
printf("%d", *n)
}
n++ moves the pointer sizeof(int) bytes forward.
精彩评论