Hello,

I have a program assignment that I have no idea what it's asking for honestly. I've tried to read all I can about it, but I do not understand. I tried my hand at some code, but it's only returning the address of course.

Here is my attempted code:

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;


int main()
{
    int a[5];
    int (*ptr_array)[5];

    for (int i = 0; i < 5; i++)
    {
        cout << "Enter array value: " << endl;
        cin >> *ptr_array[i];
    }

    cout << "The beginning of the array is: " << ptr_array << endl;

    return 0;

}

Here are the instructions:

Write a program that defines an array of integers and a pointer to an integer. Make the pointer point to the beginning of the array. Then, fill the array with values using the pointer (Note: Do NOT use the array name.). Enhance the program by prompting the user for the values, again using the pointer, not the array name. Use pointer subscript notation to reference the values in the array.

Mind you I'm in a beginning C++ class so please no advanced programs, I can only use the techniques that have been taught so far, which is up to basic level pointers. Thanks!

Write a program that defines an array of integers

int a[5];

and a pointer to an integer

int *ptr;

Make the pointer point to the beginning of the array.

ptr = &a[0];

Now you should be able to finish the rest. Hint: to move the pointer to the next member of the array all you have to do is increment the pointer, much like you would increment an integer.

Edited 3 Years Ago by Ancient Dragon

I still don't understand what the program is asking for, I understand that I need to use the pointer to fill the array, but what does my output need to be. From my earlier code I modified it, but it just keeps printing the address.

int main()
{
    int a[5];
    int *ptr_arr;
    ptr_arr = &a[0];

    for (int i = 0; i < 5; i++)
    {
        cout << "Enter array value: " << endl;
        cin >> *ptr_arr;
        ptr_arr++;
    }


    cout << "The beginning of the array is: " << ptr_arr << endl;

    return 0;

}

but what does my output need to be.

According to the requirements you posted, output is not specified. Do what you want, or output nothing at all.

By the time the program reaches line 15 the address of ptr_array has been changed to somewhere beyond the end of the array. If you want to print the first item in the array then you need to reset the pointer back to the beginning, like you did on line 5.

You can't print the entire array at one time like you are trying to do on line 15. Create a loop similar to line 7 and instead of cin on line 10 use cout.

This question has already been answered. Start a new discussion instead.