Getting Size of Array from Pointer in C
In C , determining the size of an array passed as a pointer can be challenging. Arrays exhibit "array/pointer equivalence," where an array can decay to a pointer when passed as a function argument. This poses the problem of determining the array's size accurately.
To overcome this issue, we cannot rely on sizeof() as it returns the size of the pointer, which is typically 4 or 8 bytes, not the number of elements in the array. Instead, we must explicitly pass the array's size as an additional argument.
Solution:
Modify the function header to include a parameter for the array size:
int largest(int *list, size_t size)
Pass the array's size along with the pointer to the function:
static const size_t ArraySize = 5; int array[ArraySize]; int result = largest(array, ArraySize);
By passing the size explicitly, the function can appropriately determine the number of elements in the array.
Alternative Approach:
If we only have a pointer to the array and not the original array variable, we can calculate the size using the following formula:
size = sizeof(pointer_variable) / sizeof(array_element_type)
For example, if we have a pointer int *ptr to an array of integers with an unknown size, we can determine the size as follows:
size = sizeof(ptr) / sizeof(int);
The above is the detailed content of How Can I Get the Size of an Array Passed as a Pointer in C ?. For more information, please follow other related articles on the PHP Chinese website!