Search code examples
carrayspointersc99compound-literals

assigning a compound literal to an array pointer gives both the expected result and rubbish at the same place and time?


#include <stdio.h>

int main(void) {
    int a[5], *p, i;
    p = a;
    p = (int []){1, 2, 3, 4, 5};
    for (i = 0; i < 5; i++, p++) {
        printf("%d == %d\n", *p, a[i]);
    }
    return 0;
}

Lo and behold (YMMV):

$ gcc -O -Wall -Wextra -pedantic -std=c99 -o test test.c; ./test
1 == -1344503075
2 == 32767
3 == 4195733
4 == 0
5 == 15774429

Printing the array through pointer arithmetic shows that it indeed holds an integer sequence of 1 to 5, yet printing again what is supposedly the same array expressed through indeces gives uninitialized crap. Why?


Solution

  • You only assign to p, never to a, so a is never initialized.

    int a[5], *p, i;
    // a uninitialized, p uninitialized
    p = a;
    // a uninitialized, p points to a
    p = (int []){1, 2, 3, 4, 5};
    // a uninitialized, p points to {1, 2, 3, 4, 5}