1 year ago

#376405

test-img

Nicolás Rivera

Sort merge two piles in C

I'm learning C and encountered with this issue: So I have a code that sorts 2 arrays (a and b) into a new array c. That should be easy enough, but the code isn't working and I'd like to ask for help, what am I doing wrong?

#include <stdio.h>
#include <stdlib.h>

void print_array(int size, int data[], char *str)
{
    int i;
    printf("%s\n", str);

    for (i=0; i<size; i++)
        printf("%d\t", data[i]);
    printf("\n-----------\n");
}
void merge (int size, int a[], int b[], int c[]) // a and b same size
{
    int i=0, j=0, k=0;
    while (i<size && j<size)
        if (a[i]<b[j])
            c[k++]=a[i++];
        else
            c[k++]=b[j++];
    while (i<size)
        c[k++]=a[i++];
    while (j<size)
        c[k++]=b[j++];
    print_array(size, c, "\nSORTED C:  \n");
}
int main(void)
{
    
    #define SIZE 10
    int a[SIZE]; // = {78, 80, 75, 82, 83};
    int b[SIZE];
    int c[2*SIZE];
    int i;
    int sz;
    //fprintf("\nsize of c = %d \n", sizeof(c)/sizeof(int));
    for(i=0;i<SIZE;i++)
    {
        a[i]=rand()%100;   //Generate number between 0 to 99
        b[i]=rand()%100;   //Generate number between 0 to 99
    }
    print_array(SIZE, a, "\nArray a\n");
    print_array(SIZE, b, "\nArray b\n");
    merge(SIZE, a, b, c);
    print_array(SIZE, c, "\nMy sorted arrays\n");
    return 0;
}

When I run this program, it not only doesn't print the sorted array c, but also c doesn't have the length that it should have (20), instead, it only prints ten values. Why is this happening?

Furthermore, I don't understand how it is possible that I send the arrays a and b to another function, do the processing (sorting in the function merge), and then come back to main with the post-processed data (sorted c), if I'm not returning sorted c in merge. Finally, (due to this last issue) when I try to print the size of c using fprintf("\nsize of c = %d \n", sizeof(c)/sizeof(int)); The program doesn't execute correctly, and when I compile it gives me these warnings: sort_merge.c:42:13: warning: passing argument 1 of 'fprintf' from incompatible pointer type [-Wincompatible-pointer-types] fprintf("\nsize of c = %d \n", sizeof(c)/sizeof(int)); Which doesn't make sense (to me) because I've used this same expression in other codes and it works.

I took the code from a lecture, and I'm using pretty much the same code.

arrays

c

printf

mergesort

0 Answers

Your Answer

Accepted video resources