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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With