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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Is sizeof for a struct equal to the sum of sizeof of each member?
- Why does sizeof(x++) not increment x in C?
- How to find size of array in C/C++ without using sizeof ?
- Implement Your Own sizeof
- Operands for sizeof operator
- sizeof() for Floating Constant in C
- sizeof operator in C
- Difference between strlen() and sizeof() for string in C
- Anything written in sizeof() is never executed in C
- Why C treats array parameters as pointers?
- What is evaluation order of function parameters in C?
- Class template with multiple parameters
- Use of & in scanf() but not in printf()
- Why strcpy and strncpy are not safe to use?
- gets() is risky to use!
- Can we use function on left side of an expression in C and C++?
- What is use of %n in printf() ?
- Use of realloc()
- When do we use Initializer List in C++?
- Use of explicit keyword in C++
Improved By : shohamziner