Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)
I'm learning how to create a dynamic array in C, but have come across an issue I can't figure out.
If I use the code:
int num[10]; for (int i = 0; i < 10; i++) { num[i] = i; } printf("sizeof num = %li\n sizeof num[0] = %li", sizeof(num), sizeof(num[0]));
I get the output:
sizeof num = 40 sizeof num[0] = 4
This is what I'd expect to happen. However if I malloc the size of the array like:
int *num; num = malloc(10 * sizeof(int)); for (int i = 0; i < 10; i++) { num[i] = i; } printf("sizeof num = %li\n sizeof num[0] = %li", sizeof(num), sizeof(num[0]));
Then I get the output:
sizeof num = 8 sizeof num[0] = 4
I'm curious to know why the size of the array is 40 when I use the fixed length method, but not when I use malloc()
.
We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);
To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.
In c programming, the array is used to store a range of values of the same data type and it occupies some space in memory which can be either static or dynamic. The malloc is a function used in the c programming for dynamic memory allocation.
In the second case, num
is not an array, is a pointer. sizeof
is giving you the size of the pointer, which seems to be 8 bytes on your platform.
There is no way to know the size of a dynamically allocated array, you have to save it somewhere else. sizeof
looks at the type, but you can't obtain a complete array type (array type with a specified size, like the type int[5]
) from the result of malloc
in any way, and sizeof
argument can't be applied to an incomplete type, like int[]
.
Arrays are not pointers (the decay to pointers in some situations, not here).
The first one is an array - so sizeof
gives you the size of the array = 40 bytes.
The second is a pointer (irrespective of how many elements it points to) - sizeof
gives you sizeof(int*)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With