Home > Backend Development > C++ > How Can I Get the Size of an Array Passed as a Pointer in C ?

How Can I Get the Size of an Array Passed as a Pointer in C ?

Patricia Arquette
Release: 2024-12-22 03:52:12
Original
287 people have browsed it

How Can I Get the Size of an Array Passed as a Pointer in C  ?

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)
Copy after login

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);
Copy after login

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)
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template