c - sizeof(Array_Name) inside main function VS sizeof(Array_Name) inside a user defined function -
this question has answer here:
sizeof(array_name) when used in side main function returning number of bytes of array, while when used inside userdefined function retures size of pointer (and because passed function pointer).
my question that, why when sizeof(array_name) used inside main, not treated pointer?
this because array names decay pointers when passed functions. example
int main() { int arr[3] = { 1, 2, 3 }; printf("main: %zu\n", sizeof(arr)); f(arr); } void f(int *ptr) { printf("%zu", sizeof(ptr)); }
output:
main: 3 * sizeof(int) f: sizeof(int *)
(where sizeof...
replaced actual value on compiler)
also, doesnt depend on whether array declared in main
or not. rule more general: in function array declared, treated actual array. when passed argument function, converted pointer first element. why functions taking arrays take pointer first element, , size argument.
void print(const int *arr, size_t n) { size_t i; (i = 0; < n; ++i) printf("%d\n", arr[i]; }
Comments
Post a Comment