Home >Backend Development >C++ >How Can I Get the Size of an Array When Using Pointers in C ?

How Can I Get the Size of an Array When Using Pointers in C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-03 05:41:10229browse

How Can I Get the Size of an Array When Using Pointers in C  ?

Get the Size of an Array Using a Pointer in C

Determining the number of elements in an array is crucial when operating on arrays. However, when working with arrays as pointers in C , this task becomes challenging.

C inherits "array/pointer equivalence" from C. Arrays can decay into pointers when passed as function arguments, allowing code like:

void func(int* ptr);

int array[5];
int* ptr = array; // equivalent to 'ptr = &array[0]'
func(array); // equivalent to 'func(&array[0]);'

In your case, you are passing a pointer to the array elements instead of the array itself. Therefore, the pointer alone doesn't contain size information.

To handle this, you should explicitly pass the size as an additional argument:

static const size_t ArraySize = 5;
int array[ArraySize];
largest(array, ArraySize);

Customizing the function to accept the array pointer and its size directly:

int largest(int* array, size_t size);

You can also leverage syntactic sugar to define the array with a fixed size:

void func(int array[5]);

However, this is syntactic sugar for an array pointer declaration:

void func(int* array);

When you have the array itself and not just a pointer, you can obtain the number of elements using:

sizeof(array) / sizeof(array[0]);

The above is the detailed content of How Can I Get the Size of an Array When Using Pointers in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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