Can someone please explain, why list-printing cycle with pointers works perfectly fine from main(), but refuses to work from separate function when called.

#include <stdio.h>

void listPrint (int a[], int k)
    int *arr = a, *quan = &k;
    for ( ; arr < quan; ++arr )
        printf("%i ", *arr);

int main (void)
    int n = 16;
    int array[16] = { 34, -5, 6, 0, 12, 100, 56, 22, 44, -3, -9, 12, 17, 22, 6, 11 };

    void listPrint (int a[], int k);

    int *arr = array, *quan = &n;

    for ( ; arr < quan; ++arr)
        printf("%i ", *arr);

    listPrint(array, n);

    return 0;

Nothing in the C standard guarantees how function arguments are read (meaning in which order) or in what order they're going to be stored in memory. In the case in main, the memory address where n was stored is a higher number than the address where array is stored. That's why your loop works. This seems to not be the case when the arguments are passed to the function. Your for loop never enters because "arr" is larger than "quan".

You shouldn't really rely on the value stored in a pointer to determine how far a for loop should run. It's not really reliable because you don't know which addresses the compiler will use for your variables.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .