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
Release: 2024-12-03 05:41:10
Original
282 people have browsed it

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

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

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

int largest(int* array, size_t size);
Copy after login

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

void func(int array[5]);
Copy after login

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

void func(int* array);
Copy after login

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

sizeof(array) / sizeof(array[0]);
Copy after login

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!

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