On Tue, Oct 22, 2013 at 9:40 AM, Steven D'Aprano <
steve+comp.lang.pyt...@pearwood.info> wrote:

> On Tue, 22 Oct 2013 15:39:42 +0000, Grant Edwards wrote:
>
> >> No, I was thinking of an array. Arrays aren't automatically initialised
> >> in C.
> >
> > If they are static or global, then _yes_they_are_.  They are zeroed.
>
> Not that I don't believe you, but do you have a reference for this?
> Because I keep finding references to uninitialised C arrays filled with
> garbage if you don't initialise them.
>
> Wait... hang on a second...
>
> /fires up the ol' trusty gcc
>
>
> [steve@ando c]$ cat array_init.c
> #include<stdio.h>
>
> int main()
> {
>   int i;
>   int arr[10];
>   for (i = 0; i < 10; i++) {
>     printf("arr[%d] = %d\n", i, arr[i]);
>     }
>     printf("\n");
>     return 0;
> }
>
> [steve@ando c]$ gcc array_init.c
> [steve@ando c]$ ./a.out
> arr[0] = -1082002360
> arr[1] = 134513317
> arr[2] = 2527220
> arr[3] = 2519564
> arr[4] = -1082002312
> arr[5] = 134513753
> arr[6] = 1294213
> arr[7] = -1082002164
> arr[8] = -1082002312
> arr[9] = 2527220
>

> What am I missing here?
>

The array you made there is an auto variable (stack), not a static or a
global. Try one of the following (neither has been tested):

Static:

int main()
{
  int i;
  static int arr[10];
  for (i = 0; i < 10; i++) {
    printf("arr[%d] = %d\n", i, arr[i]);
    }
    printf("\n");
    return 0;
}



Global:

int arr[10];
int main()
{
  int i;
  for (i = 0; i < 10; i++) {
    printf("arr[%d] = %d\n", i, arr[i]);
    }
    printf("\n");
    return 0;
}

As for a reference:
http://stackoverflow.com/questions/1831290/static-variable-initialization
 and
http://stackoverflow.com/questions/3373108/why-are-static-variables-auto-initialized-to-zero,
both of which then reference the C++ standard.


>
> --
> Steven
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to