Hi everybody, I am new to the programming world and I have an assignment that I need to write an array then a new array that needs to allocated dynamically and, then, populated in reverse order before being displayed all within a function.

Here is what I have so far

#include "stdafx.h"
#include <iostream>
using namespace std;


void main() 
{
	int array1[6] = {2, 4, 6, 8, 10, 12};
	int *nums = array1;

	cout << "The numbers are:\n";
	cout << *nums << " ";

	while(nums < &array1[5])
	{ 
		nums++;

		cout<< *nums << " ";
	}

        // I know this is where the dyn. allocating comes in but how?

       system("pause");
       return;

Recommended Answers

All 7 Replies

In your program, nums is just a pointer to the first element of array1.

If your assignment includes a requirement to allocate a new array, why not start by doing that and then figuring out what to do with it?

>>a new array that needs to allocated dynamically

Your program has not done that. And the loop on lines 15 - 19 is useless, just delete it.

First, call new to allocate an array of the same number of integers as the original array.

Next, use a for loop that counts from N (where N is the number of elements) to 0 and copy the data from the original array to the new array. Do not -- repeat DO NOT, change the value of nums variable because it must remain the same as it was after the call to new. Instead, just index into it, such as nums[i] = array1[j];

How do you count N to 0?

Subtract.

I have changed a few things but it is telling me "The variable 'j' is being used without being initialized"

#include "stdafx.h"
#include <iostream>
using namespace std;



int main()
{
       int array1[6] = {2, 4, 6, 8, 10, 12};
       int *nums = array1;
	   int i,j;

       cout << "The numbers are:\n";
       cout << *nums << " ";

       while(nums < &array1[5])
       { 
              nums++;

              cout<< *nums << " ";
       }


        int *ptrnewArray;

        ptrnewArray = new int[6];

        for (i = 0; i < 5; i++)
                ptrnewArray[i] = array1[j];

        for (j = 0; j < 5; j--)
                cout << ptrnewArray[j] << endl;

        delete [] ptrnewArray;

        system("pause");
        return 0;
}

Well, it is. Look on line 29: You're using array[j] but you have never given a value to j.

You should do an increment and a decrement in the same loop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.