+ 1

sizeof funtion with a loop in c!

why the result of using sizeof function in the second example is differing from the first example: int c[5]={1,2,3,4,5}; // Example 1 : for(int i=0;i<5;i++) { printf("c[%d] = %d \n",i,c[i]); } printf("\n\n\n\n"); //Example 2 : for(int i=0;i<sizeof(c);i++) { printf("c[%d] = %d\n",i,c[i]); }

7th Feb 2023, 3:32 PM
Hasna Oulaiz
9 Answers
+ 5
The variable c[5] is an initialised array of 5 integers. This implies that memory of sizeof(int) * 5 will be sequentially allocated and has the values 1, 2, 3, 4, 5 The first loop ranges from 0 to 4, you're printing to the console the items in c.. in each body of the loop, the index operators on c will be offset by c[1] and evaluated as value of c[2] = address at (2 * sizeof(int)) = 3 c[n] = address at (n * sizeof(int)) = K However, the second loop ranges from 0 to sizeof(int) * 5 which is 20 (assuming sizeof(int) is 4). Getting items past the valid address of an array results to what's called an UNDEFINED behavior and that's why you'll get random numbers printed out. Some part of the second loop, you're trying to print items within c[5] to c[19] which doesn't exist
7th Feb 2023, 3:56 PM
Mirielle
Mirielle - avatar
+ 4
As a size note, you can use: sizeof(c) / sizeof(int) to get the number of elements in the int array c.
7th Feb 2023, 4:58 PM
Lochard
Lochard - avatar
+ 4
sizeof operator returns array size in bytes. To find length of array : https://www.freecodecamp.org/news/how-to-find-the-size-of-an-array-in-c-with-the-sizeof-operator/amp/
7th Feb 2023, 5:01 PM
Jayakrishna 🇮🇳
+ 3
Jayakrishna 🇮🇳 thank you 🙏
8th Feb 2023, 5:55 PM
Hasna Oulaiz
+ 2
Mirielle thank you for this explanation, I appreciate it 🙏
8th Feb 2023, 5:54 PM
Hasna Oulaiz
+ 2
You're welcome..
8th Feb 2023, 6:22 PM
Jayakrishna 🇮🇳
+ 2
It's not necessary that sizeof (int) or sizeof(double) returns 4 or 8 bytes in c++.. some machine does not represent numbers as 16bits or float as 32bits or 64bits etc and in such instances, sizeof(type) may varies
9th Feb 2023, 4:53 AM
Mirielle
Mirielle - avatar
+ 2
Tbh I wouldn't say "for sure" 😃 but I think everything depends on what make up a byte which is the sizeof char. char are represented with the lowest most accessible number of bits. If sizeof(char) which is constantly 1byte is represent as 8bits, then it's safe to say that on a 32 machine, sizeof(int) will be 4 because 8bits makes up a byte. in conclusion, 8bits may not be 1byte in some instances too
9th Feb 2023, 5:22 AM
Mirielle
Mirielle - avatar
+ 1
Lochard thank you 🙏
8th Feb 2023, 5:54 PM
Hasna Oulaiz