Home > Backend Development > C++ > body text

Why Does `sizeof()` Return Unexpected Results for Array Parameters in C Functions?

Susan Sarandon
Release: 2024-11-11 07:31:02
Original
368 people have browsed it

Why Does `sizeof()` Return Unexpected Results for Array Parameters in C   Functions?

Why sizeof() Doesn't Work the Same for Array Parameters in C Functions

In C , arrays decay into pointers when passed to functions, rendering the use of sizeof() unreliable for determining array size. To understand this, let's analyze the following function:

int length_of_array(int some_list[])
{
    return sizeof(some_list) / sizeof(*some_list);
}
Copy after login

Issue with the Array Parameter

The parameter some_list is declared as an array, but the function signature is effectively equivalent to int length_of_array(int* some_list). This is because arrays decay into pointers in function parameters.

Effect on sizeof()

Using sizeof(some_list) in this context calculates the size of the pointer, resulting in a value of 1. Dividing by sizeof(*some_list) (the size of an integer) yields 1.

Example

In the given example, despite the array num_list containing 15 elements, the function length_of_array() consistently returns 1, as seen in the output:

This is the output from direct coding in the
int main function:
15
This is the length of the array determined
by the length_of_array function:
1
Copy after login

Solution Using Template Functions

To determine array size in functions, one can use template functions and pass the array by reference:

template<size_t N>
int length_of_array(int (&amp;arr)[N])
{
    return N;
}
Copy after login

In this case, the template parameter N captures the known size of the array, allowing sizeof() to return the correct value.

The above is the detailed content of Why Does `sizeof()` Return Unexpected Results for Array Parameters in C Functions?. 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