I'll assume that the idea is to practice using pointers.
In this case some things were missing and others are incorrect, and the code should look like this:
int main()
{
int j,aux,i;
int *A=(int*) malloc(n*sizeof(int));
srand(time(NULL));
for(int i=0; i<n; i++, A++)
{
*A=rand()%50*10;
}
A-=n;
cout<<"Vetor aleatorio.";
for(int i=0; i<n; i++, A++)
{
cout<< *A<<" ";
}
A-=n; //faltou aqui voltar de novo para trás
for(i=0; i < (n-1); i++)
{
for(j=0; j < (n-i-1); j++)
{
if(A[j] > A[j+1]) //sem *
{
aux=A[j];
A[j]=A[j+1]; //sem *
A[j+1]=aux; //sem *
}
}
}
cout<<"Vetor ordenado:\n";
for(i=0; i<n; i++, A++) //faltou o A++
{
cout<<*A<<" ";
}
}
I removed the comments I had in the code to emphasize what I put in the face of the changes I made.
The places where I removed *
as if(*A[j] > *A[j+1])
do not need to because accessing a position with the []
notation is already accessing the value indicated.
View the code working on Ideone
My suggestion is that you do not use this pattern unless it is for mere pointers. Moving forward with a pointer from an array forward in for
to in order to return back with A-=n;
is complicated, obscure and error-prone, as you may have already noticed.
Following my advice and if you are not just practicing pointers, I suggest that you write the program like this:
int main()
{
int *A=(int*) malloc(n*sizeof(int));
srand(time(NULL));
for(int i=0; i<n; i++){
A[i]=rand()%50*10;
}
cout<<"Vetor aleatorio.";
for(int i=0; i<n; i++){
cout<< A[i]<<" ";
}
for(int i=0; i < (n-1); i++){
for(int j=0; j < (n-i-1); j++){
if(A[j] > A[j+1]){
int aux=A[j];
A[j]=A[j+1];
A[j+1]=aux;
}
}
}
cout<<"Vetor ordenado:\n";
for(int i=0; i<n; i++){
cout<<A[i]<<" ";
}
return 0;
}
Note that in this release I only declare the variables where they are strictly necessary rather than at the top of the program. This ends up simplifying and improving the readability of the code.
It would also be better to declare the array statically like this:
int A[n];
But I'll assume that the statement in heap
was a requirement of the program.
See also this version on Ideone