Weird behavior when printing array in C?

The breaking condition in for loop is wrong! Which causes an index-out-of bound problem as i exceeds the maximum index value that is 10 because array length is just 11. The loop break condition should be < length of array( =11) but not < size of array.
Value of sizeof(intArray) is equals to 11 * sizeof(int) (= 44).

To understand it read: sizeof Operator:

6.5.3.4 The sizeof operator, 1125:

When you apply the sizeof operator to an array type, the result is the total number of bytes in the array.

According to this when sizeof is applied to the name of a static array identifier (not allocated through malloc()/calloc()), the result is the size in bytes of the whole array rather then just address. That is equals to size of each elements multiply by the length of array.
In other words: sizeof(intArray) = 11 * sizeof(int) ( as intArray length is 11 ). So suppose if sizeof(int) is 4-bytes then sizeof(intArray) is equals to 44.

Below a code example and its output will help you to understand further(read comments):

int main(){
    int intArray[11] = {1, 2, 8, 12, -13, -15, 20, 99, 32767, 10, 31};
    int i = 0;
 
    printf("sizeof(intArray):  %d\n", 
            sizeof(intArray)                       //1. Total size of array
    ); 
    printf("sizeof(intArray[0]):  %d\n", 
            sizeof(intArray[0])                    //2. Size of one element
    ); 
    printf("length:  %d\n", 
            sizeof(intArray) / sizeof(intArray[0]) //3. Divide Size
    );    
    return 0;
}

Output:

sizeof(intArray):  44    //1. Total size of array:  11 * 4 = 44
sizeof(intArray[0]):  4  //2. Size of one element:  4
length:  11              //3. Divide Size:          44 / 4 = 11 

One can check the working code @ideone, note: I am assuming size of int is 4.

Now notice as sizeof(intArray) is 44 that is more then length of array hence the condition is wrong and you have Undefined behavior in the code at runtime. To correct it replace:

for(i=0; i < sizeof(intArray); i++)
//           ^--replace-----^
//            wrong condition = 44

With:

for(i=0; i < sizeof(intArray) / sizeof(intArray[0]); i++)
          // ^------------------------------------^
          // condition Corrected = 11 


 

To calculate length of array, I simply divided total size of array by the size of one element and code is:

sizeof(intArray) / sizeof(intArray[0])   // 44 / 4 = 11
     ^                 ^
total size of       size of first element
array   
  

Leave a Comment