Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

pointers

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?

like image 512
talena6 Avatar asked May 29 '10 18:05

talena6


1 Answers

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;
like image 58
zneak Avatar answered Oct 03 '22 19:10

zneak