I want to make a sort statement by using a function. The problem is, I cannot return it back to the main()
function. What's the problem? I also tried the void.
int sort_func(int sort[]) {
int swap = 0;
for (int i = 0; i < 5; i ) {
for (int j = 0; j < 4; i ) {
if (sort[j] > sort[j 1]) {
swap = sort[j];
sort[j] = sort[j 1];
sort[j 1] = swap;
}
}
}
return sort[5];
}
What is the problem in the code?
CodePudding user response:
You don't need to return
anything. The array is being passed into the function via an int*
pointer, so the code is directly manipulating the elements of the caller's array.
Also, your 2nd for
loop is incrementing i
when it should be incrementing j
instead.
How is the caller's array declared, exactly? The loops inside your function require the sort
parameter to point at an int[]
array with at least 5 elements. However, the function's declaration does not convey or enforce that requirement, so the caller is free to pass in however many elements it wants, and if that size is fewer than 5 then your code will have undefined behavior. You should at least have the caller pass in the actual number of elements as another parameter, eg:
void sort_func(int sort[], int size) {
int swap = 0;
for (int i = 0; i < size; i ) {
for (int j = 0; j < (size-1); j ) {
if (sort[j] > sort[j 1]) {
swap = sort[j];
sort[j] = sort[j 1];
sort[j 1] = swap;
}
}
}
}
int arr[5];
...
sort_func(arr, 5);
Otherwise, if you strictly require 5 elements, then enforce that by taking a pointer to an array with exactly 5 elements, eg:
void sort_func(int (*sort)[5]) {
int swap = 0;
for (int i = 0; i < 5; i ) {
for (int j = 0; j < 4; j ) {
if ((*sort)[j] > (*sort)[j 1]) {
swap = (*sort)[j];
(*sort)[j] = (*sort)[j 1];
(*sort)[j 1] = swap;
}
}
}
}
int arr[5];
...
sort_func(&arr);
Or, use a reference instead of a pointer, eg:
void sort_func(int (&sort)[5]) {
int swap = 0;
for (int i = 0; i < 5; i ) {
for (int j = 0; j < 4; j ) {
if (sort[j] > sort[j 1]) {
swap = sort[j];
sort[j] = sort[j 1];
sort[j 1] = swap;
}
}
}
}
int arr[5];
...
sort_func(arr);