I’ll assume the idea is to practice using pointers.
In this case some things are 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 on the code to emphasize the ones I made.
The places where I removed the *
as if(*A[j] > *A[j+1])
do not need because when accessing a position with the notation []
already this to access the value pointed.
See code working on Ideone
My suggestion is that you do not use this pattern unless it is by mere pointer practice. Move a pointer forward from an array on for
for at last to turn back with A-=n;
is complicated, obscure and conducive to error, as you may have noticed.
Taking my advice and in case you’re not just practicing pointers, I suggest 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 version I only declared the variables where they are strictly necessary instead of at the top of the program. This simplifies and improves the readability of the code.
It would also be better to declare the array statically like this:
int A[n];
But I’m going to assume that the statement on heap
was a requirement of the program.
See also this version on Ideone
The idea is to practice pointers ? Why increment the array pointer in
for
withA++
and then doA-=n;
is inappropriate and propitious to errors, being this one of the causes of the error– Isac
even correcting the increment of the array, continues with the same error.
– Carlos Ferreira