简体   繁体   English

如何重置指向特定数组位置的指针?

[英]How do I reset my pointer to a specific array location?

I am a brand new programming student, so please forgive my ignorance.我是一个全新的编程学生,所以请原谅我的无知。 My assignment states:我的任务规定:

Write a program that declares an array of 10 integers.编写一个程序,声明一个包含 10 个整数的数组。 Write a loop that accepts 10 values from the keyboard and write another loop that displays the 10 values.编写一个从键盘接受 10 个值的循环,然后编写另一个显示 10 个值的循环。 Do not use any subscripts within the two loops;不要在两个循环内使用任何下标; use pointers only.只使用指针。

Here is my code:这是我的代码:

#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
     const int NUM = 10;
     int values[NUM];
     int *p = &values[0];
     int x;
     for(x = 0; x < NUM; ++x, ++p)
     {
         cout << "Enter a value: ";
         cin >> *p;
     }  
     for(x = 0; x < NUM; ++x, ++p)
     {
         cout << *p << "  ";
     }
    return 0;
}

I think I know where my problem is.我想我知道我的问题在哪里。 After my first loop, my pointer is at values[10], but I need to get it back to values[0] to display them.在我的第一个循环之后,我的指针位于 values[10],但我需要将其恢复到 values[0] 以显示它们。 How can I do that?我怎样才能做到这一点?

You can do exactly as you did first when you assigned p :您可以完全按照您在分配p时所做的那样:

p = &values[0];

Besides, arrays are very much like pointers (that you can't change) to statically allocated memory.此外,数组非常类似于指向静态分配内存的指针(您无法更改)。 Therefore, the expression &values[0] evaluates to the same thing that just values does.因此,表达式&values[0]的计算结果为同样的事情,仅仅values一样。 Consequently,最后,

p = &values[0];

is the same as是相同的

p = values;

Did your assignment say that you had to print the numbers in order?你的作业有没有说你必须按顺序打印数字? If not, you could have some fun by printing them in reverse:如果没有,您可以通过反向打印来获得一些乐趣:

while (p != values)
{
    cout << *(--p) << " ";
}

(Just use this code for learning.) (只需使用此代码进行学习。)

if the assignment say that you had to print the numbers in order, should modify it as below:如果作业说您必须按顺序打印数字,则应将其修改如下:

for (x = 0; x < NUM; ++x, p++)
{
    cout << *(p-NUM) << "  ";
}

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

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