Calculate array length within C language function

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

Declares an integer array of length 10 within the main function and forwards it to the func function to output different lengths of the calculated array and the calculated array length within the main function.

#include <stdio.h>

void func(int * arr) {
    int len = sizeof(arr) / sizeof(int);
    printf("%d \n", len);
}
int main() {
    int num[10];
    printf("%d \n", sizeof(num) / sizeof(int)); // 10 Output
    func(num); // 2 Output

    return 0;
}

I thought num and arr would be calculated exactly the same, but why is it calculated differently?

c dev-c++

2022-09-20 11:40

1 Answers

of handing over into the main function of function from func num is just starting address of the array. That the func The function is only starting address of the array, because I can see only the information, have no way to know the size of the array.

It is common to use n inside a function after changing the function prototype to the void func(int*arr, intn) format and adding the array length to n when calling the function. For example, in the main function, run func(num, sizeof(num)/sizeof(num[0])).


2022-09-20 11:40

If you have any answers or tips


© 2022 pinfo. All rights reserved.