Hello everyone. I'm trying to solve an exercise by bubblesort ordering method and dynamic allocation (no pointers and no dynamic allocation the exercise gets easier, however, the teacher asked to do with AD). The exercise is simple, it is to say how many times the problem will turn, to pass the amount of numbers to be rearranged, and to play on the screen. Here is the code:
#include<stdio.h>
#include<stdlib.h>
main(){
int qt,n,i,j,aux;
int *p;
scanf("%d",&qt);
while(qt!=0){
scanf("%d",&n);
p = (int *) calloc(n, sizeof(int));
for(i=0; i<n; i++){
scanf("%d",(p+i));
}
/* for(i=0; i<n; i++){
printf("%d\n",*p); /* Neste for, estou testando se o ponteiro está pegando os números, e está */
++p;
} */
for(i=0; i<n-1; i++){
for(j=n-1; j>i; j--){
if(*p < *(p-1)){
aux = *p;
*p = *(p-1);
*(p-1) = aux;
}
}
}
for(i=0; i<n; i++){
printf("%d ",*p);
++p;
}
printf("\n");
free(p);
qt--;
}
}
Anyway, the error happens in the sort method, when in the end, I start the reordered values, only appear garbage. I know I'm wrong in the sort method, I've tried to put a ++ p or --p, but it did not work. I think that * (p-1) is wrong. Could someone tell me the error? Thankful.