1

I am trying to print an array however I am not getting the desired output, weird numbers appear after the loop finishes printing the pre-defined array.

Code is:

#include <stdio.h>    
int main(){    
    int intArray[11] = {1,2,8,12,-13,-15,20,99,32767,10,31};
    int i=0;        
    for(i=0;i<sizeof(intArray);i++){
        printf("%d\n",intArray[i]);
    }
}

Output:

1
2
8
12
-13
-15
20
99
32767
10
31
11
1629976468
2674040
2665720
1627423265
1
2665616
-2147417856
1629976534
1629976468
2674040
0
1627423172
1629976532
0
1629110043
0
0
0
0
0
0
0
0
0
0
0
1629976538
0
1629956432
2674276
0
1627407935
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
KAKAK
  • 879
  • 7
  • 16
  • 32
  • Perhaps read that beginner's C programming guide more carefully...!? –  Aug 02 '13 at 06:36
  • 1
    This question appears to be off-topic because it is about reading and spoon-feeding the documentation for OP. –  Aug 02 '13 at 06:36
  • Thanks for the example code that actually reproduces your observations. Now you should add some details on the steps you made in order to figure out what's wrong yourself. Have you looked up the documentation of the functions/operators you've used? Have you tried to print out the loop index and the stopping condition? – moooeeeep Aug 02 '13 at 07:19

5 Answers5

14

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   
  
Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • Thanks, could you please explain why it should be done like that? `sizeof(intArray)/sizeof(intArray)` – KAKAK Aug 02 '13 at 06:03
  • That condition is still incorrect, the expression will give `1` as numerator and denominator are same! – Rohan Aug 02 '13 at 06:03
  • You're again making the same *assertion* without any reasoning? – devnull Aug 02 '13 at 06:13
  • @GrijeshChauhan Questioning how the code in question would lead to a buffer overflow doesn't imply that I downvoted you. – devnull Aug 02 '13 at 06:54
  • Essentially, this method "normalizes" to determine the number of elements associated with a variable. In more complicated examples, you might have an array of structures divided by the size of one structure to get the number of structures in the array. – JackCColeman Aug 02 '13 at 07:57
  • Unfortunately this method is only available in edge cases, i.e. for arrays that have not (yet) decayed to a pointer. +1 if you add a paragraph on the general case, if you make your answer more concise and if you improve your english. – moooeeeep Aug 02 '13 at 08:00
4

sizeof gives you the size of the array in bytes, not elements. To get the number of elements, divide by the size of only one element:

for(i = 0; i < (sizeof intArray / sizeof intArray[0]); i++)
{
    printf("%d\n", intArray[i]);
}

It's worth noting that this only works for array types, it doesn't work when you have allocated a block of memory using malloc.

dreamlax
  • 93,976
  • 29
  • 161
  • 209
3

You need to change sizeof(intArray) to

sizeof(intArray)/sizeof(int)

This will give the number of the array elements.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • thanks, but why should we define sizeof(int)? how is it different from `sizeof(intArray)/sizeof(intArray)` – KAKAK Aug 02 '13 at 06:04
  • 1
    @DeepakTivari Because `sizeof` an array name gives the size of the entire array in bytes. `sizeof(intArray)/sizeof(intArray)` is always `1`. – Yu Hao Aug 02 '13 at 06:06
  • @DeepakTivari: You're dividing the size of the entire array by the size of only one element, this gives you the number of elements in the array. This answer differs from the others in that `sizeof(int)` is hardcoded. If you were to change the type of `intArray` to `long` for example, you would need to ensure you updated this condition. The other answers do not have this problem. – dreamlax Aug 02 '13 at 06:07
2

Update

for(i=0;i<sizeof(intArray);i++)

to

for(i=0;i<sizeof(intArray)/sizeof(intArray[0]);i++)

sizeof(intArray) gives total size of array in bytes not number of elements in the array.

Rohan
  • 52,392
  • 12
  • 90
  • 87
2

You have declared intArray as an array of 11 ints. Each int occupies a certain number of bytes in memory (typically four). So the size of the whole intArray is 11 * 4 = 44 bytes.

When you say i < sizeof(intArray), you are therefore saying i < 44. But your array has only 11 elements, not 44! So your loop will continue past the array bounds. It will continue to read four-byte chunks and interpret them as integers, and print out the garbage values.

That is why all the answers are saying that you need to have your loop condition be

i < sizeof(intArray) / sizeof (intArray[0])

You need to divide the size of the entire array by the size of a single element to get the number of elements in the array. Since you already know the number of elements, you could keep it simpler and just say

i < 11

but for more general cases where you might not know the size of the array, you need to use the other suggested loop condition.

verbose
  • 7,827
  • 1
  • 25
  • 40