I am getting junk when I try to print the new array when i return it from function

So your divided_by is working fine tho I would optimize it a bit to make it consume less memory and be faster.

Anyways the problem is your for loop in the main...

for(int i=0;i<sizeof(r);i++)
{
    printf("%d\t",r[i]);
}

You declared r as an int pointer which means that r shows the place of the first integer in the array. hence the sizeof(r) returns 8 (size of an int pointer, which is 8 bytes). In this specific example, your function divided_by returns a pointer containing 3 elements but you print 8 of them cuz of that, you get the 3 correct elements (1, 5, 49) and 5 junks.

A solution might be writing a function that calculates the length of your array for example...

int len(int *r)
{
        int len;

        len = 0;
        while (r[len])
                len++;
        return len;
}

Make sure that the system initializes not used memory in r to zero. Or use calloc() instead of malloc(). This will ensure that len() function works fine on any system.

And then you use this function in the condition of your for loop. Like this...

for(int i=0;i<len(r);i++)
{
    printf("%d\t",r[i]);
}

After this, you will get the desired output.


As many have noted, the main problem in your code is that you use sizeof(r) as if were the number of available items in the array. Since the return value must be the new array, you need to find a way to pass the number of items or signal the end. I would use a sentinel value of 0 at the end of the array (I assume nobody will pass a 0 to check if it is divisible). Other options include saving the length in the first position of the array.

I modified a little divided_by to make ir more efficient and cleaner: now it stops checking when it finds the first divisor. I also free in main the allocated memory in divided_by.

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

int* divided_by(int* s1, unsigned int n1, int* s2, unsigned int n2)
{
    int *r =(int *) malloc ((n1+1) * sizeof(int)); /* n+1 for the sentinal*/
    if(!r)
    {
        printf("couldn't allocate memery");
        exit (1);
    }
    int i=0, c=0;
    while(i < n1)
    {
        int j=0;
        while ((j < n2) &&  (s1[i] % s2[j])) /* once it failed, stop checking*/
        {
             j++;
        }
         if(j == n2)
         {
             r[c] = s1[i];
             c++;
         }
        i++;
    }

    r[c] = 0; /*sentinel */
    return r;
}

int main() {
    int s1[]={1,10, 5, 4, 21, 49, 24};
    int s2[]={2,3};
    int *r= divided_by(s1, 7, s2, 2);
    for(int i=0 ; r[i] != 0 ; i++) /* until we find the sentinel*/
    {
        printf("%d\t",r[i]);
    }
    free(r); /* Don't forget to release the memory*/
    return 0;
}