reverse an array unexpected result

// i use dev c++

i write this code to reverse an array and save the result in the same one
if n=3 i expect
a[0]=0 a[1]=1 a[2]=2 (before rev is OK but after calling rev)

a[0]=2 a[1]=1 a[2]=0 (expected result )
but i get
n=3
console out
-----------------------------------
n
3
a[0]=0
a[1]=1
a[2]=2
a[0]=2293572
a[1]=4469856
a[2]=4199425
Press any key to continue . . .
--------------------------------------------


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <cstdlib>
#include <iostream>

using namespace std;

void rev(int a[],int n);

int main(int argc, char *argv[])
{
    int n;
    cout<<"n\n";
  cin>>n;
 int a[n];
 for(int i=0;i<n; i++)
 {a[i]=i;
 cout<<"a["<<i<<"]="<<a[i]<<"\n";}
 rev(&a[n],n);
    
    
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

void rev (int  a[],int n)
{int T[n];
for(int i=0;i<n; i++)
 {T[i]=a[i];}
 
 for(int i=0;i<n; i++)
 {a[i]=T[n-i-1];
 cout<<"a["<<i<<"]="<<a[i]<<"\n";}
 }
If the size of the array is n then valid indices are from 0 to n-1, so a[n] is out of bounds. What you probably meant to do is to pass a pointer to the first element in the array rev(&a[0],n);, or rev(a,n); will also work.
Line 13 is not technically legal C++. The size of the array needs to be a constant.

At line 17, a[n] is past the end of the array a. If a has n elements, then those elements have indices from 0 to n - 1.

Your code would be much easier to read and understand if you learnt to use a sensible indentation style.
thanks for you answers
Peter87
MikeyBoy
You're welcome!
Topic archived. No new replies allowed.