user11954200
user11954200

Reputation:

What does an array look like when it's initialized

I am working through K&R's C book, and have come across arrays, that I had some questions about:

1. What does an array look like when it's initialized. For example:

int word_lengths[10];

Does this start as [0,0,0,0,0,0,0,0,0,0,0]? Or [null,null,null,null,null,null,null,null,null,null]. Or something different? Basically I'm trying to conceptualize what an array looks like before it's values are set.

And 2. Is the following required to initialize everything at 0, or is this done automatically, and it's only used to be explicit in defining the elements in the array?

// initialize the array
for (int i=0; i<10; i++ ){
    ndigit[i] = 0;
}

Upvotes: 0

Views: 135

Answers (1)

Barmar
Barmar

Reputation: 782498

Automatic arrays are not initialized by default. Global and static arrays are initialized to all 0.

So if you have a program like this:

int global_array[10];

int main(int argc, char *argv[]) {
    int local_array[10];
    // code here
    return 0;
}

global_array will be initialized as if you'd written

int global_array[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

But local_array contains unspecified values. You can do it with a loop as you show. Reading a value before it's initialized results in undefined behavior.

You can also specify just a single value in the initialization list; it will default all the rest to 0. So you can write:

int local_array[10] = {0};

and it's equivalent to

int local_array[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

None of this is specific to arrays, the same is true for scalar values and structures. Automatic variables are uninitialized, global and static variables are initialized to 0.

Upvotes: 5

Related Questions