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. Write a loop that accepts 10 values from the keyboard and write another loop that displays the 10 values. 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. How can I do that?
You can do exactly as you did first when you assigned 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. 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) << " ";
}
精彩评论