简体   繁体   English

循环和内存管理中的C ++指针算术?

[英]C++ pointer arithmetic in a loop and memory management?

I am getting started with C++. 我正在开始使用C ++。 I wanted to understand the different outputs while playing around with this snippet of code. 在尝试这段代码时,我想了解不同的输出。

int main()
{
    int i = 3;
    int *ptr = &i; //stores address of the i
    while(*(ptr)--) //the same as i--
    {
        cout << *ptr << endl;
    }
}

When I run this code I understand that the deferenced value of ptr, which is "i", gets 1 subtracted from it and the loop exits when "i" equals 0. But when I use while(*ptr--) instead of while(*(ptr)--) I get a list of random integers which eventually go down to 0 and the loop breaks. 当我运行这段代码时,我了解到ptr的推定值为“ i”,它减去了1,并且当“ i”等于0时循环退出。但是当我使用while(* ptr--)而不是while时(*(ptr)-)我得到了一个随机整数列表,这些整数最终下降为0,并且循环中断。

To my understanding when I use *ptr-- I am subtracting a byte(size of one int) from the initial address of &i(*ptr) with each loop. 据我了解,当我使用* ptr时,我每次循环都从&i(* ptr)的初始地址中减去一个字节(一个int的大小)。 But why does the program terminate eventually? 但是为什么程序最终会终止? No matter what the value of "i" is, the program prints 23 random numbers with the last one being 0 and the loop exits. 无论“ i”的值是多少,程序都会打印23个随机数,最后一个为0,然后退出循环。 Should I not get an overflow error since the program runs out of memory? 由于程序内存不足,是否应该没有溢出错误?

However, when I use while(ptr--) the program does go into an infinite loop. 但是,当我使用while(ptr--)时 ,程序确实进入了无限循环。 What exactly is happening? 到底是什么情况?

Thank you very much. 非常感谢你。

(ptr) is the same as ptr , thus (ptr)-- is the same as ptr-- . (ptr)是一样的ptr ,从而(ptr)--是相同的ptr--

*ptr-- IS NOT the same as i-- ! *ptr--i--

You are applying operator-- to the right side of the pointer. 您正在将operator--应用于指针的右侧 The suffix/postfix operator-- has a higher precedence than operator* . 后缀/后缀operator-- 优先operator* So, *ptr-- is the same as *(ptr--) , not (*ptr)-- like you are expecting. 因此, *ptr--*(ptr--)相同,而不是(*ptr)--就像您期望的那样。

IOW, ptr-- gets evaluated first, which returns a copy of the current pointer and then decrements the pointer , and then you are dereferencing the copied pointer to retrieve the value that was previously being pointing at. IOW, ptr--被求值,它返回当前指针的一个副本,然后递减该指针 ,然后您要取消引用复制的指针以检索以前指向的值。

That is why you are seeing garbage - you are decrementing the pointer into memory that does not belong to you. 这就是为什么看到垃圾的原因-您正在将指针递减到不属于您的内存中。

To simply decrement the int and not the pointer, use (*ptr)-- instead. 要简单地减小int而不是指针,请使用(*ptr)-- IOW, dereference the pointer first, then decrement the value being pointed at, eg: IOW,首先解引用指针,然后递减所指向的值,例如:

int main()
{
    int i = 3;
    int *ptr = &i; //stores address of the i
    while((*ptr)--) //the same as i--
    {
        cout << *ptr << endl;
    }
}

Live demo 现场演示

Parenthesis and operator precedence matter! 括号和运算符优先级很重要!

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

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