Reputation: 3
So I'm trying to apply (in C) randomly generated numbers to an array which will be sorted with Quick sort. There is no problem with generating numbers and sorting, but at the end of the code I have an error telling me there was a problem with memory reading.
#include <stdlib.h>
#include <time.h>
void generate(int AR[], int n){
srand((unsigned int) time(NULL));
for(int i=0;i<n;i++){
int num = (rand()%100);
AR[i]=num;
}
}// end of generate
void swap(int *a, int *b){
int temp=*a;
*a=*b;
*b=temp;
} //end of swap
int sort(int AR[], int beg, int end){
int pivot= AR[end];
int a=(beg-1);
for(int i=beg; i<=end-1; i++){
if(AR[i]<pivot){
a++;
swap(&AR[i], &AR[a]);
}//end of if
} //end of i<end-1
swap(&AR[a+1], &AR[end]);
return (a+1);
} //end of sort
void Quick_sort(int AR[], int beg, int end){
if(beg<end){
int placed_PV=sort(AR, beg, end);
Quick_sort(AR, beg, placed_PV-1);
Quick_sort(AR, placed_PV+1, end);
} //end of if beg<end
}//end of Quick sort
int main(){
int AR[]={};
int n=10;
generate(AR, n);
printf("\n");
printf("Nieposortowana tablica:");
for(int i=0; i<n;i++)
printf("%d,", AR[i]);
printf("\n");
Quick_sort(AR, 0, n-1);
printf("Posortowana tablica:");
for(int i=0;i<n;i++)
printf("%d,", AR[i]);
printf("\n");
} //end of code
error message is
error: memory read failed for 0x4e00000000
Thread 1: EXC_BAD_ACCESS (code=1, address=0x4e00000000)
Where is the mistake I've made?
Upvotes: 0
Views: 44
Reputation: 1885
you have this:
int AR[]={};
int n=10;
which is wrong because this array AR
has only one element(due to this initialization) ,so you can't access ten elements of it.
fix like this
int AR[10]={0};
Upvotes: 1