Home > Backend Development > C++ > How to Determine the Size of an Array Passed as a Function Argument in C ?

How to Determine the Size of an Array Passed as a Function Argument in C ?

Patricia Arquette
Release: 2024-11-09 10:36:02
Original
646 people have browsed it

How to Determine the Size of an Array Passed as a Function Argument in C  ?

Array Size Determination in C Function Parameters

Unlike in the main function, determining the size of an array passed as an argument to a function in C using sizeof() requires a reference template. This is because arrays decay to pointers when passed to functions.

Array Decay to Pointers

Consider the following code snippet:

int length_of_array(int some_list[]);
Copy after login

Despite the declaration with square brackets, some_list decays to an integer pointer int* when passed as an argument. As a result, sizeof(some_list) returns the size of a pointer, not the array size.

Reference Template Solution

To determine the size of an array correctly, use a reference template. For example:

template<size_t N>
int length_of_array(int (&amp;arr)[N]) {
  std::cout << N << std::endl; // Outputs the correct array size
  return N;
}
Copy after login

Exception: Multidimensional Arrays

There is one exception to the array decay rule. Multidimensional arrays retain their dimensionality and are not passed as pointers. Hence, sizeof() can be used directly to determine their size:

int a[3][4];
std::cout << sizeof(a) / sizeof(a[0]); // Output: 4 (number of columns)
Copy after login

The above is the detailed content of How to Determine the Size of an Array Passed as a Function Argument 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