简体   繁体   English

C++ 指针增量

[英]C++ pointer increment

Please help me understand how the value of q is initially 1 and later changes to 0.请帮助我了解 q 的值如何最初为 1,后来变为 0。

Code:代码:

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

Output: Output:

1527896876
1527897120
1
1527896880
1527897124
1527897124
0
int *p, *q; p = &i; printf("%u\n%u\n%u\n",p,q,*q);

int* is a wrong type for the format specifier %u. int*是格式说明符 %u 的错误类型。 If you pass an argument of wrong type, then the behaviour of your program is undefined.如果您传递了错误类型的参数,那么您的程序的行为是未定义的。


 printf("%u\n%u\n%u\n",p,q,*q); *q++=*p++;

Here, q has an indeterminate value.这里, q具有不确定的值。 It doesn't point to any object.它不指向任何 object。 You indirect through the pointer to access an object that it points to.您可以通过指针间接访问它指向的 object。 Which is a contradiction because it doesn't point to any object.这是一个矛盾,因为它没有指向任何 object。

Indirecting through an indeterminate pointer results in undefined behaviour.通过不确定的指针间接导致未定义的行为。


The behaviour of your program is undefined.您的程序的行为是未定义的。 That explains everything about the behaviour of the program.这解释了有关程序行为的一切。

I think what happens is that here我想发生的事情是这里

*q++=*p++;

the post-increment operator of q is executed after the assignment. q 的后自增运算符在赋值后执行。 So, you basically set the value of q to p, and then you increment it.因此,您基本上将 q 的值设置为 p,然后将其递增。 Also, i don't think the increment operator of p does anything.另外,我认为 p 的增量运算符没有任何作用。

For a better understanding look at the following example为了更好地理解看下面的例子

#include <stdio.h>
int main() {
  int i = 10;
  int *p;
  int *q = new int[2];
  q[0] = 9;
  q[1] = 99;
  p = &i;
  printf("%u\n", *q);
  *q++ = *p++;
  printf("%u\n", *q);
  printf("%u", *--q);
  return 0;
}
9
99
10

Notice how, in the end q points to the next element, thanks to the post-increment operator.请注意,最后 q 如何指向下一个元素,这要归功于后增量运算符。

Anyway, i have no idea what you are trying to do.无论如何,我不知道你想做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM