I'm new to C and having a problem with pointers. I've been unable to find the answer online or through my peers, so here I am.
I've been given an assignment to:
- Create an array of 20 random integers
- print out the integers
- sort the array in ascending order
- print it out again
When I compile the program with GCC and run, I get a segmentation fault. I've narrowed it down to happening when I try and set the value of number[i] or number[k] in the sort function. Any help would be appreciated.
#include <stdio.h>
void sort(int* number, int n){
/*Sort the given array number , of length n*/
int temp, min;
int i, k;
for(i=0; i<n; i++){
min = i;
for(k=i+1; k<n; k++){
if(number[k]<min){
min = k;
}
}
temp = number[i];
number[i] = number[k];
number[k] = temp;
}
}
int main(){
/*Declare an integer n and assign it a value of 20.*/
int n=20;
/*Allocate memory for an array of n integers using malloc.*/
int *array = malloc(n * sizeof(array));
/*Fill this array with random numbers, using rand().*/
srand(time(NULL));
int i;
for(i=0; i<n; i++){
array[i] = rand()%1000+1;
}
/*Print the contents of the array.*/
for(i=0; i<n; i++){
printf("%d\n", array[i]);
}
/*Pass this array along with n to the sort() function of part a.*/
sort(&array, 20);
/*Print the contents of the array.*/
printf("\n");
for(i=0; i<n; i++){
printf("%d\n", array[i]);
}
return 0;
}
Here are the compile errors I get:
Q3.c: In function âmainâ:
Q3.c:31: warning: implicit declaration of function âmallocâ
Q3.c:31: warning: incompatible implicit declaration of built-in function âmallocâ
Q3.c:34: warning: implicit declaration of function âsrandâ
Q3.c:34: warning: implicit declaration of function âtimeâ
Q3.c:37: warning: implicit declaration of function ârandâ
Q3.c:46: warning: passing argument 1 of âsortâ from incompatible pointer type
Q3.c:9: note: expected âint *â but argument is of type âint **â
int[20].sizeof(array)is not rite you meantsizeof(*array)?. moreover "<stdlib.h>" is necessary for malloc()