Reputation: 41
What's wrong with this merge sort usage?
I'm trying to sort an array of size 9 as given in main().
However, I'm using the merge_sort method and it gives me the error: "ISO C forbids nested functions" for every function.
When I delete the arraycpy function these messages will no longer appear, so it's obviously a problem with "arraycpy".
Note that I can't use the string.h library since I'm limited to only these 3.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void merge(int a[], int na, int b[], int nb, int c[])
{
int ia, ib, ic;
for(ia = ib = ic = 0; (ia < na) && (ib < nb); ic++)
{
if(a[ia] < b[ib]) {
c[ic] = a[ia];
ia++;
}
else {
c[ic] = b[ib];
ib++;
}
}
for(;ia < na; ia++, ic++) c[ic] = a[ia];
for(;ib < nb; ib++, ic++) c[ic] = b[ib];
}
void arraycpy(int *dest, int *src, int n)
{
int i;
int *src_p, *dst_p;
src_p = (int*)src;
dst_p = (int*)dest;
for (i = 0; i < n; i++) {
*(dst_p+i) = *(src_p+i);
}
void internal_msort(int a[], int n, int helper_array[])
{
int left = n/2;
int right = n/2;
if (n < 2)
return;
internal_msort(a, left, helper_array);
internal_msort(a + left, right, helper_array);
merge(a, left, a + left, right, helper_array);
arraycpy(a, helper_array, n*sizeof(int));
}
void merge_sort(int a[], int n)
{
int *tmp_array = malloc(sizeof(int) * n);
internal_msort(a, n, tmp_array);
free(tmp_array);
}
void rem_sort(int array[], int size)
{
merge_sort(array, size);
}
int main()
{
int array[] = {3,55,72,4,21,6,9,0,4};
merge_sort(array, 9);
for (int i=0;i<9;i++)
printf("%d | ", array[i]);
return 0;
}
Upvotes: 2
Views: 21235
Reputation: 455
I had the same error that complained on my main file. This file had not bracket imbalances. This was in my opinion strange. But the error was produced by an other file that I had included in the main.c file.
Check edited #include files if you can not find the open "}"
Upvotes: 0
Reputation: 12270
You missed a closing braces for for
loop in the function arraycpy
void arraycpy(int *dest, int *src, int n)
{
int i;
int *src_p, *dst_p;
src_p = (int*)src;
dst_p = (int*)dest;
for (i = 0; i < n; i++) {
*(dst_p+i) = *(src_p+i);
}
// ^^^
}
So, the next braces is being taken as the braces for the for
loop, and thus when you define the next function, it is being defined inside the next function arraycpy
Upvotes: 3