IS IT POSSIBLE TO PASS AN ARRAY INTO A FUNCTION AND THEN CALCULATE THE PRIME NUMBERS OUT OF THE LIST?

Dani AI

Generated

Yes — an array can be passed to a C function (it decays to a pointer), but the length must be passed explicitly. The common, safe pattern is: take const int *arr and a size_t n, scan the array to identify primes, and return results either by filling a caller-provided buffer, returning a malloc'd array plus a count, or by filtering in-place. The list-based example from shows the iteration idea; the same loop becomes an index-based loop for arrays.

A compact two-pass example: count primes, malloc an output buffer of the exact size, then fill it.

#include <stdlib.h>
#include <stddef.h>

/* trial-division test */
static int is_prime_int(int n)
{
    if (n < 2) return 0;
    if (n % 2 == 0) return n == 2;
    for (int d = 3; (long long)d * d <= (long long)n; d += 2)
        if (n % d == 0) return 0;
    return 1;
}

/* returns malloc'ed array of primes (caller must free); out_count set to number found */
int *find_primes_in_array(const int *arr, size_t n, size_t *out_count)
{
    if (!arr || !out_count) return NULL;
    *out_count = 0;

    for (size_t i = 0; i < n; ++i)
        if (is_prime_int(arr[i])) ++*out_count;

    if (*out_count == 0) return NULL;

    int *out = malloc(*out_count * sizeof(int));
    if (!out) { *out_count = 0; return NULL; }

    size_t j = 0;
    for (size_t i = 0; i < n; ++i)
        if (is_prime_int(arr[i])) out[j++] = arr[i];

    return out;
}

Notes and choices: trial division is fine for small-to-moderate integers. For many numbers or repeated queries where values are bounded, a Sieve of Eratosthenes across the value range is much faster. For very large integers, use a probabilistic test (Miller–Rabin). Memory strategies include in-place filtering (overwrite the input with primes), dynamic append with doubling realloc, or the two-pass exact-allocation shown above. Always check for NULL inputs, treat values < 2 as non-prime, cast when squaring to avoid overflow, and free any malloc'd output. And, as reminded earlier, no need to shout — the code will work better without it.

Recommended Answers

All 2 Replies

yes, AND YOU DON'T HAVE TO SHOUT SO LOUD!

You could handle it some thing like this:

void getPrimesInList( Clist* in, Clist* out )
{
    Node* cur = in->head;
    while( cur )
    {            
        if( isPrime(cur->value) )
            push_backClist( out, cur );
        cur = cur->next;
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.