0

What mistake I made here? I wanted to print the array.

code: #include <stdio.h> int main() { int single[5] = {1, 2, 3, 4, 5}; for(int c = 0; c < sizeof(single); c++) { printf("%d\n", single[c]); } return 0; } output: 1 2 3 4 5 629 16 7 1 0 -395439167 32759 0 0 20 0 -395394984 32759 -395394912 32759

12th May 2023, 2:35 PM
Basant Kumar
Basant Kumar - avatar
2 ответов
+ 9
sizeof() will get you the total amount of memory allocated to the array. But each element takes up multiple bytes, depending on the data type. To calculate the length of the array, divide the total size by the size of a single element: sizeof(single) / sizeof(single[0]) See more in StackOverflow: https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c Fixed code: #include <stdio.h> int main() { int single[5] = {1, 2, 3, 4, 5}; int LENGTH = (int) (sizeof(single) / sizeof(single[0])); for(int c = 0; c < LENGTH; c++) { printf("%d\n", single[c]); } return 0; }
12th May 2023, 2:48 PM
Tibor Santa
Tibor Santa - avatar
+ 8
sizeof operator returns total storage required for argument. So there sizeof(single) returns 20. To find length, use int len = sizeof(single) / sizeof(single[0] ) . So there, 20/4 = 5 , here total storage 20bytes, and 4 represents size for each element, so 5 is length of array. so use len instead then in loop...
12th May 2023, 2:48 PM
Jayakrishna 🇮🇳