C program sizeof | SoloLearn: Learn to code for FREE!

0

C program sizeof

# include <stdio.h> void print(int *arr) { int n = sizeof(arr)/sizeof(arr[0]); printf ("%d\n ", sizeof(arr)); printf ("%d\n\r ", sizeof(arr[0])); //printf ("%d ", n); int i; for (i = 0; i < n; i++) printf("%d ", arr[i]); } int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; printf ("%d\n ", sizeof(arr)); printf ("%d\n\r ", sizeof(arr[0])); print(arr); return 0; }

3/27/2019 4:36:25 AM

M.SWAMINATHAN

3 Answers

New Answer

+2

Line 5 contains a mistake: when you pass an array you don't pass it's size, so sizeof(arr) will be the size of the pointer type (32 or 64 bits), not of the whole array.

+2

M.SWAMINATHAN In main int arr[] is a statically allocated array of type int so sizeof(arr) = sizeof(int) * no of elements in the array. assuming sizeof(int) = 4 bytes the answer will be 4 * 8 (no of elements) = 32 bytes sizeof(arr[0]) = size of first element of the array. Since arr[0] is of type int, it's size equals sizeof(int) = 4 bytes When you pass the arr to the function, it is passed as pointer to an int, so inside the function sizeof(arr) = sizeof(int*) = 4 or 8 bytes depending on the platform. At sololearn sizeof(int*) = 8 bytes Inside the function the sizeof(arr[0]) is still equal to sizeof(type of first element) which is int, hence sizeod(arr[0]) = 4 You are calculating n = sizeof(arr) / sizeof(arr[0]) which give n = 8/4 = 2 so your for loop executes 2 times and prints first two elements of the array.

-2

i need explanation about output of this program