Jordan Kasper Jordan Kasper - 23 days ago 8
C Question

Sort an array in a C function

So I need to pass the array to the function sort and have it sort it, it works outside but cant get it to work inside the function. Need to pass in the pointers just not sure how.

#include <stdio.h>

void sort(int *number, int n) {

/* Sort the given array number, of length n */
int temp = 0, j, i;

for (i = 1; i < n; i++) {
for (j = 0; j < n - i; j++) {
if (number[j] > number[j + 1]) {
temp = number[j];
number[j] = number[j + 1];
number[j + 1] = temp;
}
}
}
}

int main() {
int n = 20;
int *ptr = malloc(n * sizeof *ptr);
int i = 0;

while (i < n) {
ptr[i] = rand() % 100;
i++;
}
int j = 0;
while (j < n) {
printf("%d , ", ptr[j]);
j++;
}
void sort(ptr, n);
printf("\n");

int x = 0;
while (x < n) {
printf("%d , ", ptr[x]);
x++;
}
}

Answer

void sort(ptr, n); should just be sort(ptr, n);

I could be wrong on this, but I believe in a C compiler, the first form is interpreted as a function prototype and the second an actual function call.