How to reset my pointer to a specific array location?

I am a new student in programming, so please forgive my ignorance. My destination states:

Write a program declaring an array of 10 integers. Write a loop that takes 10 values ​​from the keyboard and write another loop that displays 10 values. Do not use indexes inside 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 has the values ​​[10], but I need to return it to the values ​​[0] to display them. How can i do this?

+6
c ++ pointers
source share
2 answers

You can do what you did when you assigned p :

 p = &values[0]; 

In addition, arrays are very similar to pointers (which you cannot change) to statically allocated memory. Therefore, the expression &values[0] is evaluated the same as only values . Consequently,

 p = &values[0]; 

coincides with

 p = values; 
+7
source share

Was your task to say that you had to print the numbers in order? If not, you could have fun by typing them in the reverse order:

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

(Just use this code for training.)

0
source share

All Articles