Home > Backend Development > C++ > Why Does `sizeof` Return an Incorrect Array Size When Passing an Array to a C Function?

Why Does `sizeof` Return an Incorrect Array Size When Passing an Array to a C Function?

Linda Hamilton
Release: 2024-12-14 15:35:16
Original
859 people have browsed it

Why Does `sizeof` Return an Incorrect Array Size When Passing an Array to a C Function?

Array Size Discrepancy When Passing to Function

The sizeof() operator reports an inaccurate value for an array when passed to a function. Consider the following code snippet:

#include <stdio.h>

void test(int arr[]) {
    int arrSize = (int)(sizeof(arr) / sizeof(arr[0]));
    printf("%d\n", arrSize); // 2 (incorrect)
}

int main() {
    int point[3] = {50, 30, 12};

    int arrSize = (int)(sizeof(point) / sizeof(point[0]));
    printf("%d\n", arrSize); // 3 (correct)

    test(point);

    return 0;
}
Copy after login

When called from main(), the sizeof() operator accurately reports the size of the array, but within the test() function, it underestimates the size by one element. This disparity arises because when an array is passed to a function in C, it decays to a pointer referencing the array's first element. Consequently, sizeof(arr) calculates the pointer's size rather than the underlying array's size.

To remedy this issue, the size of the array should be explicitly passed as a separate parameter to the function:

void test(int arr[], size_t elems) {
    // ...
}

int main() {
    int point[3] = {50, 30, 12};
    // ...
    test(point, sizeof(point) / sizeof(point[0]));
    // ...
}
Copy after login

Alternatively, for dynamically allocated arrays (not shown here), the standard C library function stdlib.h can be used to accurately obtain the array's size.

The above is the detailed content of Why Does `sizeof` Return an Incorrect Array Size When Passing an Array to a C Function?. 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