[英]Why is the integer not incremented in this code?
Can anyone explain what I'm doing wrong here to not get 11 as my output? 谁能解释我在这里做错了什么而没有得到11作为我的输出?
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
. n++
递增指针n
,而不是整数由指向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: 如果我们调用malloc变量x
,那么您的程序将执行以下操作:
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]. 您将n [0]设置为10,然后打印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]. malloc()不会初始化它给您的内存,因此打印出来的内容是不可预测的-这就是n [1]中发生的任何垃圾。
You can get 11 as your output with this code: 使用以下代码,您可以获得11作为输出:
void foo {
int *n = malloc(sizeof(int));
*n = 10;
(*n)++;
printf("%d", *n)
}
n ++将指针sizeof(int)个字节向前移动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.