C ++用指针反向打印数组内容-为什么此方法有效? [英] c++ print array contents in reverse with pointer - why does this method work?

查看:72
本文介绍了C ++用指针反向打印数组内容-为什么此方法有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自C ++ Early Objects-Gaddis,第8版.我在SO上注意到类似的问题,但是没有一个问题可以回答这个问题.考虑这个简单的程序:

From C++ Early Objects - Gaddis, 8th Edition. I note similar questions on SO, but none that answer this aspect. Consider this simple program:

// This program uses a pointer to display
// the contents of an array.
#include <iostream>
using std::cout;

int main(){
    const int SIZE = 8;
    int set[ ] = {5, 10, 15, 20, 25, 30, 35, 40};
    int *numPtr;   // Pointer   

    // Make numPtr point to the set array.
    numPtr = set;

    // Use the pointer to display the array elements
    cout << "The numbers in set are:\n";
    for (int index = 0; index < SIZE; index++) {
        cout << *numPtr << " ";
        numPtr++;
    }

    // Display the array elements in reverse order
    cout << "\nThe numbers in set backwards are:\n";
    for (int index = 0; index < SIZE; index++) {
        numPtr--;
        cout << *numPtr << " ";
    }
    return 0;
}

工程,我测试了!但是从概念上讲,numPtr指向数组集合"的起始地址,那么从起始地址向后递增" numPtr怎么不会在第二个(反向)for循环的第一次迭代中引起段错误?重申这个问题,numPtr如何知道"在数组"set"的最后一个元素的地址处开始? 保持谦虚,我正在介绍CS II ...谢谢!

Works, I tested it! But conceptually, numPtr is pointing to the starting address of the array "set", so how does incrementing numPtr "backwards" from the starting address not cause a segfault on the first iteration of the second (reversing) for loop? Restating the question, how is numPtr "knowing" to begin at the address of the last element of the array "set"? Be gentle, I'm in Intro to CS II... thanks!

推荐答案

在开头,numPtr指向集合的开头.然后,在第一个操作中 ,递增numPtr ,直到它指向集合的末尾.

At the beginning, numPtr points to the beginning of the set. Then, in the first operation, you increment the numPtr until it points to the end of the set.

到达第二个迭代时,numPtrset+sizeof(set)-1处,因此您可以递减以将您的设置向后移.

When you reach the second iteration, numPtr is at set+sizeof(set)-1, so you can decrement it to get your set backwards.

这篇关于C ++用指针反向打印数组内容-为什么此方法有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆