views:

104

answers:

2

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?

+7  A: 

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;
zneak
Thank you so much!
ohtanya
@ohtanya: No problem. If it works well enough, you can click the check mark under the rating of the answer to accept the answer. :)
zneak
Nikolai N Fetissov
@Nikolai N Fetissov: The only practical difference I can see between `int* const foo` and `int foo[3]` is what `sizeof` yields. Is there any other?
zneak
Try declaring `extern char* buffer;` in a header and then defining `char buffer[256];` in a `.c` file. The compiler will clearly tell you that types are different. I know, it's a bit subtle. If you're interested - pick up a copy of "Expert C Programming: Deep C Secrets" by Peter Van Der Linden - it has a whole chapter about this.
Nikolai N Fetissov
A: 

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.)

Daniel Trebbien