Reputation: 31
please interpret for me about the result that the following code run.
#include <stdio.h>
int get_array_size(int *arr){
return sizeof(arr)/sizeof(int);
}
int main(int argc, char const *argv[]){
int arr[10];
printf("%d\n", sizeof(arr)/sizeof(int));
printf("%d\n",get_array_size(arr));
printf("%d\n",arr[10]);
printf("%d\n",get_array_size(arr));
return 0;
}
which is:
10
2
0
2
Upvotes: 0
Views: 62
Reputation: 1957
printf("%d\n", sizeof(arr)/sizeof(int));
sizeof(arr) returns size of array in bytes. Since it is an int array of length 10, "sizeof(arr)" will be "10*sizeof(int)". You are deviding it by sizeof(int). So output will be 10.
printf("%d\n",get_array_size(arr));
This is interesting! You are passing address of "arr" to get_array_size(). In that function first you are getting size of address. The address size depends on the machine you are running, i.e. In 32-bit machine address size will be 4bytes and in 64-bit machine it will be 8bytes. I think you are using 64-bit machine so sizeof(arr) is returning 8. But sizeof(int) is 4bytes. So effectively it is 8/4 = 2.
printf("%d\n",arr[10]);
Your array size is 10, so you can access from arr[0] to arr[9]. arr[10] is not part of your array. That address might be used for some other variable. You are just writing whatever present in that address. The output is completely random. I think that address had 0 when you executed the program, so you got the output as 0.
printf("%d\n",get_array_size(arr));
This is repeated print (Output is 2).
Upvotes: 1
Reputation: 434
#include <stdio.h>
int get_array_size(int *arr){
return sizeof(arr)/sizeof(int);
}
int main(int argc, char const *argv[]){
int arr[10];
printf("%d\n", sizeof(arr)/sizeof(int));//10
printf("%d\n",get_array_size(arr));//1
printf("%d\n",arr[10]);//if a[9] adress=x a[10] prints undefined value from x+4 adress
printf("%d\n",get_array_size(arr));1
return 0;
}
When you call the function local variable arr
is given priority so 4/4 always gives 1 when called
Upvotes: 1
Reputation: 2933
All sizes are in bytes.
sizeof(arr)/sizeof(int) = size of array / size of int = 40/4 = 10
get_array_size(arr) = size of array pointer(which is 4) / size of int = 4/4 = 1.
arr[10] = the eleventh entry of array(array size=10). (undefined number).
Upvotes: 1