Question

I have created this simple program to reverse the order of my array using pointers. I have created the same type of program using JAVA however, I feel like the pointer are giving me a problem.

Error Description:

My error is coming out of my reverse function. Instead of giving me the integers in reverse, it seems like it is outputting memory addresses. For example, 0x003456, 0xx45268, .......; instead of outputting the actual numbers which I have placed in my first array. Now I am more than positive that my pointers is what is causing this mix up, I just can't pin point exactly where my mistake is. If someone can lead me in the right directions I would be very thankful.

Code:

#include <iostream>
#include <iomanip>

using namespace std;

void reverseArray(int *[], int);
void firstArrayValue( int [], int);

void main ()
{
  const int SIZE = 10;
  int firstArray [SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  int *arrayPointer[SIZE];

  for ( int x = 0; x < SIZE ; x++)
  {
   arrayPointer[x] = &firstArray[x];
  }

   cout << "The Values In Your First Array Is the Following : \n \n" ;
   firstArrayValue(firstArray, SIZE);
   reverseArray(arrayPointer, SIZE);
   system("pause");
  }
void reverseArray(int *incoming_Array[], int size)
{
int *temp;
for (int i = 0; i < size/2; ++i) 
{
    temp = incoming_Array [size-i-1];
    incoming_Array [size-i-1] = incoming_Array [i];
    incoming_Array [i] = temp;
}

for (int i = 0; i < size; ++i) 
{
    cout << incoming_Array [i] << " ";
}

system("pause");
}

void firstArrayValue( int num[], int size)
{
for (int x = 0; x < size; x++)
{
    cout << num [x] << " " ;
}
}
Was it helpful?

Solution

void reverseArray(int incoming_Array[], int size) //instead of int *incoming_Array[]
{
    int *temp;
    for (int i = 0; i < size/2; ++i) 
    {
        temp = incoming_Array [size-i-1];
        incoming_Array [size-i-1] = incoming_Array [i];
        incoming_Array [i] = temp;
    }
    for (int i = 0; i < size; ++i) 
    {
        cout << incoming_Array [i] << " ";
    }
}

OTHER TIPS

As the comment under your question mentioned, you need to deference the pointers in your array to get actual values. Change your print line to the following to explicitly deference.

cout << *(incoming_Array [i]) << " ";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top