Home > Backend Development > C++ > Why Does `sizeof` Give Different Array Sizes Inside and Outside a C Function?

Why Does `sizeof` Give Different Array Sizes Inside and Outside a C Function?

Susan Sarandon
Release: 2024-12-19 10:51:09
Original
850 people have browsed it

Why Does `sizeof` Give Different Array Sizes Inside and Outside a C Function?

Why Array Size Calculation Differs Inside a Function in C

When passing an array to a function, C automatically decays the array into a pointer to its first element. This pointer carries the address of the first array element but not its size.

Consider this example:

#include <stdio.h>

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

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

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

    test(point);

    return 0;
}
Copy after login

In main, sizeof(point) correctly gives the size of the entire array (12 bytes). However, within test, sizeof(arr) yields 4 bytes (the size of an integer pointer), resulting in an incorrect array size calculation (missing one element).

To resolve this, the array size must be explicitly passed as a separate parameter:

void test(int arr[], size_t elems) {
    int arrSize = elems;
    /* ... */
}

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

Note that sizeof(point)/sizeof(point[0]) works for stack-allocated arrays but not for dynamically allocated arrays since it relies on the underlying decay mechanism.

The above is the detailed content of Why Does `sizeof` Give Different Array Sizes Inside and Outside 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