Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of uninitialized elements in array of C language

I have an array of 3 elements. But I only want to initialize 2 of them. I let the third element blank.

unsigned char array[3] = {1,2,};
int main(){
  printf("%d",array[2]);
    return 0;
}

The print result is 0. I tested it on IAR, and some online compiler.

Is there any C rule for the value of third element? Is there any compiler filling the third element by 0xFF ? (Especially cross compiler)

like image 895
Ngo Thanh Nhan Avatar asked Sep 22 '15 04:09

Ngo Thanh Nhan


People also ask

What is the value of uninitialized array in C?

As with traditional methods, all uninitialized values are set to zero. If the size of the array is not given, then the largest initialized position determines the size of the array.

What is stored in an uninitialized array?

If the array is not initialized at the time of declaration or any time after that then it will contain some random values in each memory position.

What is the default value of elements of an Uninitialised array?

Answer. Explanation: From the Java Language Specification: Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10): For type byte, the default value is zero, that is, the value of (byte)0 .

Are array values initialized to 0?

The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list. Designated Initializer: This initializer is used when we want to initialize a range with the same value.


1 Answers

Yes, the C standard does define what happens in this case. So no, there should be no C standard compliant compiler that intialises with 0xFF in this case.

Section 6.7.9 of the standard says:

Initialisation

...

10 ...If an object that has static or thread storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
  • if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

...

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

like image 89
kaylum Avatar answered Oct 04 '22 18:10

kaylum