Solved

Reverse array and pointers?

Posted on 2007-11-13
15
2,410 Views
Last Modified: 2013-12-14
Ok! This is the assignment I was given this week. I know hold on its a long one... lol. I don't think he was very descriptive and I've asked him to please be a little more descriptive and 3 days later no response, anyways here it is: (Does my code look right cause it works the way I believe it is supposed to.)

Write a C++ function ReverseArray using "pointer notation" that will write out the elements of an array of int in reverse order.

Here is my code:

#include <iostream>

using namespace std;

void reverseArray();

int main()
{
      cout << "Enter five integers: ";
      reverseArray();

      return 0;
}
void reverseArray()
{
      int numbers[5];
      int* p_numbers = &numbers[5];
      int counter;
            for (counter = 0; counter < 5; counter++)
      {
            cin >> numbers[counter];
            cout << "Enter five integers: ";
      }
      cout << endl;

      cout << "The numbers in reverse are: ";

      for (counter = 4; counter >= 0; counter--)
            cout << numbers[counter] << " ";
      cout << endl;
}
0
Comment
Question by:jschmuff
  • 3
  • 3
  • 3
  • +4
15 Comments
 
LVL 6

Accepted Solution

by:
SeanDurkin earned 250 total points
Comment Utility
Take a look at this webpage, it demonstrates pointer notation:

http://co-5.college-online.com/joan_albright/CPT_235_files/Pointer_Notat_vs_Array_Notat.htm

What you want to do is set int *p_numbers equal to the beginning of your array, and then print them out using p_numbers, instead of accessing the numbers array directly.
0
 

Author Comment

by:jschmuff
Comment Utility
Thank you very much I will give it a shot tomorrow, as for now it is bed time for me. I believe I understand what you are saying. I will post tomorrow my new code and see if I understood correctly. Thank you again.
0
 
LVL 6

Expert Comment

by:SeanDurkin
Comment Utility
No prob... and as a side note, your professor may want you to put the values in the array with pointer notation as well. That won't be too hard to implement, either.. you just dereference p_numbers again using counter, rather than accessing the numbers array directly.
0
 
LVL 5

Expert Comment

by:abith
Comment Utility
int *start = &numbers[0];
int *end = start + (length-1);

for ( ; start<=end; start++, end--)
{
interchange the values of *start and *end
}
0
 
LVL 53

Expert Comment

by:Infinity08
Comment Utility
>> void reverseArray()

I think the point of the exercise is to make the function work for any array, meaning that you have to pass the array as a parameter to the function which will then show it in reverse.

So, the input part (cin etc.) would move to the main, and only the reverse printing is done by the function.
0
 
LVL 4

Expert Comment

by:yuy2002
Comment Utility
#include <iostream>
using namespace std;

template<class T,int size>
class Array
{
public:
    T elem[size];
    Array();
    ~Array();
    void reverseArray();
    void print();
};
template<class T,int size>
Array<T,size>::Array()
{
}

template<class T,int size>
Array<T,size>::~Array()
{
}

template<class T,int size>
void Array<T,size>::reverseArray()
{
    if(elem == NULL)
        return;
    int i=0;
    T temp[size];
    while(i<size)
    {
        temp[size-1-i] = elem[i];
        i++;
    }
    memcpy(elem,temp,size*sizeof(T));
    return;
}

template<class T,int size>
void Array<T,size>::print()
{
     int i=0;
     for(i=0;i<size;i++)
     {
         cout<<elem[i]<<endl;
     }
}
int main()
{
    Array<int,10> array;
    int i =0 ;
    for(i=0;i<10;i++)
    {
        array.elem[i] = i;
    }
    cout<<"*******Origin Array*********"<<endl;
    array.print();
    array.reverseArray();
    cout<<"*******Reverse Array*********"<<endl;
    array.print();
    return 0;
}
0
 
LVL 53

Expert Comment

by:Infinity08
Comment Utility
@yuy2002 : two things :

1) the asker clearly stated that this is a homework assignment - full code should thus not be posted according to the rules of this site.

2) KIS (keep it simple) : there is no need to use templates here ... the assignment is for an array of ints only
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 40

Expert Comment

by:evilrix
Comment Utility
Some observations about the posted solution...

>> using namespace std;
This should be discouraged as it can lead to problems with 3rd party code that may include older, non-namespaced, versions of the STL headers!

>> Array();
>> ~Array();
The compiler will auto-generate these!

>> memcpy(elem,temp,size*sizeof(T));
If elem (array of type T) is not a POD type this copy is dangerous!

>> void Array<T,size>::reverseArray()
There are smarter ways to do this. For example, you could start from each end and swap the elements until you get to the middle. You only need parse 50% off the array and you only need temporary storage that is the size of 1 element and the algorithm is simple!

>> public:    T elem[size];
Public data is a encapsulation sin!

>> if(elem == NULL)
>>        return;
Since elem is a fixed size stack array how could this predicate ever be true?

>> int i =0 ; ... array.elem[i] = i;
When indexing memory you should use size_t otherwise your code will not be portable.

IMHO this is not a good example and, as Infinity08 said, shouldn't have been posted!

-Rx.



0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
Comment Utility
>>>> IMHO this is not a good example and, as Infinity08 said, shouldn't have been posted!
The question is whether it should be 'upvalued' then by commenting each statement?

>>>> I think the point of the exercise is to make the
>>>> function work for any array, meaning that you
>>>> have to pass the array as a parameter to the
>>>> function which will then show it in reverse.

In case Infinity's suggestion 'got lost' because of the previous 'off topic' comments, I post it here again.

The consequence of the suggestion (enhanced by me) is that you should

- create the array in the main function (not in reverseArray)
- have a separate function for user input, e. g.
      bool getUserInput(int * numbers, int arrsiz);
- the reverseArray should take an int * (pointer notation) and
  should reverse the values of the array (not print them).
- finally have a 'display' function which outputs the reversed array.

You should pass the size of the array (== 5) to all functions, so that you easily can change it.

Regards, Alex
 
0
 
LVL 40

Expert Comment

by:evilrix
Comment Utility
>> should be 'upvalued' then by commenting each statement?
Qualification of assertion!
0
 

Author Comment

by:jschmuff
Comment Utility
So basically this assignment can be interpreted to code in several different ways? If so im going for simplest cause if I go ahead to stuff we haven't learned then that doesn't look good plus he will grade badly for that as well.
0
 

Author Comment

by:jschmuff
Comment Utility
Here is my new code and the output is way off what am I doing wrong??

#include <iostream>

using namespace std;

void arrayRev();

const int SIZE = 5;

int main()
{
      int numbers[SIZE];
      int* p_numbers;
      int counter;
      p_numbers = numbers;

      cout << "Enter five integers: ";

      for (counter = 0; counter < SIZE; counter++)
      {
            cin >> numbers[counter];
            cout << "Enter five integers: ";
      }
      
      cout << endl;

      arrayRev();

      return 0;
}
void arrayRev()
{
      int numbers[SIZE];
      int* p_numbers;
      int counter;
      p_numbers = numbers;

      cout << "The numbers in reverse are: ";

      for (counter = 4; counter >= 0; counter--)
            cout << *(p_numbers+counter) << " ";
      cout << endl;
}
0
 
LVL 6

Expert Comment

by:SeanDurkin
Comment Utility
You're creating a local numbers array within the arrayRev() function, but it is completely different from the one in main(). All you have to do is pass the original numbers array into arrayRev() like this:

void arrayRev(int numbers[]);

void arrayRev(int numbers[])
{
      int* p_numbers;
      int counter;
      p_numbers = numbers;

      cout << "The numbers in reverse are: ";

      for (counter = 4; counter >= 0; counter--)
            cout << *(p_numbers+counter) << " ";
      cout << endl;
}

And then inside main() you just pass it with arrayRev(numbers); But keep in mind that the numbers array inside arrayRev is just a copy of main()'s arrayRev. Even though they have the same name (which you shouldn't do anyway because it makes it harder to read), they have different scopes, so they don't interfere with each other.
0
 
LVL 4

Expert Comment

by:yuy2002
Comment Utility
Hi,evilrix

3x for your good suggestion.
>>There are smarter ways to do this. For example, you could start from each end and swap the >>elements until you get to the middle. You only need parse 50% off the array and you only need >>temporary storage that is the size of 1 element and the algorithm is simple!
0
 
LVL 53

Expert Comment

by:Infinity08
Comment Utility
I don't think you need to actually reverse the array ... just print it in reverse :

>> Write a C++ function ReverseArray using "pointer notation" that will write out the elements of an array of int in reverse order.


Your latest code looks fine except that, as SeanDurkin already pointed out, you're still not passing the array as a parameter to the function (see also my first comment in this thread).
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now