Search code examples
arrayscreturn-valuevariable-length-array

How to make use of an array returned by a function? in C language


My general goal with this question is to understand how to make use (say, print) of an array returned from an outer function. I'm using prime numbers as an example. I'm new so going in-depth explaining... Sorry if there's un-needed info or misused terms :)

I defined a function "findprimes" to find every prime between 1 and x. The function successfully prints an array of primes. However, I don't know if it returns the array of primes. And, if it does, I have no idea how to use said array in main().

This is the function 'findprimes':

int* findprimes(int x) {

    int i, j, total=0;
    int* numbers = (int*)malloc((x + 1) * sizeof(int));

    /* initialization */
    for (i = 0; i <= x + 1; i++) {
        numbers[i] = 1;
    }

    /* find primes and assign prime=1 */
    for (i = 2; i < sqrt(x); i++) {
        if (numbers[i] == 1) {
            for (j = i * i; j <= x; j = j + 2) {
                if (j % i == 0) {
                    numbers[j] = 0;
                }
            }
        }
    }

    /* count how many primes */
    for (i = 1; i <= x; i++) {
        if (numbers[i] == 1) {
            total++;
        }
    }

    /* put primes into their own array */
    int* primes = (int*)malloc(total * sizeof(int));
    for (i = 1,j=0; i <= x; i++) {
        if (numbers[i] == 1) {
            primes[j] = i;
            j++;
        }
    }

    //I want this part to be in main()
    printf("The prime numbers between 1 and %d are: ", x);
    for (i = 0; i < total; i++) {
        printf("%d ", primes[i]);
    }
    
    return primes;
}

I want to print the 'primes' array in main, not in the function 'findprimes' itself. How can I do this?

int main() {

    int n;

    do {
        printf("Enter a value for X>2: ");
        scanf("%d", &n);
    } while (n <= 2);

    findprimes(n); //This returns 'primes' array

    //I want to print 'primes' array here
}

Solution

  • Capture the return value in main():

    int *primes = findprimes(n);
    

    and use the array:

    for (int i = 0; i < some_magic_number; i++)
    {
        printf("%d\n", primes[i]);
    }
    

    and remember to free the memory:

    free(primes);
    

    In fact, you also need to free numbers in the function.

    The some_magic_number needs to be known — how does the main() function know how many elements are in the array? One way to fix that is to pass a pointer to the function that can hold the number of primes:

    int *findprimes(int n, int *num_primes)
    

    and use *num_primes = total; in the function before returning. You could call the function with:

    int some_magic_number;
    int *primes = findprimes(n, &some_magic_number);
    

    You'd probably choose an alternative name for the variable in main(), but it illustrates my point.