Consider the below program.
Output: 0 0 0 0 on a IA-32 machine.
The function fun() receives an array parameter arr and tries to find out number of elements in arr using sizeof operator.
In C, array parameters are treated as pointers (See this for details). So the expression sizeof(arr)/sizeof(arr) becomes sizeof(int *)/sizeof(int) which results in 1 for IA 32 bit machine (size of int and int * is 4) and the for loop inside fun() is executed only once irrespective of the size of the array.
Therefore, sizeof should not be used to get number of elements in such cases. A separate parameter for array size (or length) should be passed to fun(). So the corrected program is:
Please write comments if you find anything incorrect in the above article or you want to share more information about the topic discussed above.
- Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
- What is Array Decay in C++? How can it be prevented?
- Opaque Pointer
- Arrays in C Language | Set 2 (Properties)
- How arrays are passed to functions in C/C++
- Arrays in C/C++
- Function Pointer in C
- Difference between pointer and array in C?
- Initialization of variables sized arrays in C
- Are array members deeply copied?
- What is the difference between single quoted and double quoted declaration of char array?
- Write one line functions for strcat() and strcmp()
- When is copy constructor called?
- C function to Swap strings
- Why C treats array parameters as pointers?