How to calculate the length of an array in C language

(1) With the help of the sizeof() function:

#include<stdio.h>
int main()
{
// Define an integer array, and initialize and assign 9 data: 
int arr[] = {1,2,3,4,5,6,7,8, 9};
int length = 0;
// Calculate the length of the data in the array:
// The number of bytes of all data divided by the number of bytes of a data is the number of data: 
length = sizeof(arr) / sizeof(int) ;  printf("The length of the array is: %d\n",length); return 0;







Results of the :


(2) The above method will have a misunderstanding

That is when the array is passed as an argument to another function, and this function performs the same method as above, the result will not be the correct length of the array:

Test code :

#include<stdio.h>

void test(int arr[])
{
int length = 0;
length = sizeof(arr) / sizeof(int);
printf("The total number of bytes in the test_array is: %d\n ",sizeof(arr));
printf("The length of the test_ array is: %d\n",length);
}

int main()
{
// Define an integer array, and initialize and assign 9 data: 
int arr[] = {1,2,3,4,5,6,7,8,9};
int length = 0;
// Calculate the length of the data in the array:
// The number of bytes of all data divided by the number of bytes of a data The number of bytes is the number of data: 
length = sizeof(arr) / sizeof(int); 
printf("The length of the main_array is: %d\n",length); test(arr); return 0;




Results of the :


Code Analysis :

When passing an array as an actual parameter to another function, the formal parameter of the other function is equivalent to a pointer variable , because when the name of the array is used as the actual parameter , the first address of the number is used as the actual parameter , so in the test The sizeof(arr) output in the function actually gets the length of an integer array ( the number of bytes occupied ),  so the result is 8, and then divide it by the number of bytes occupied by int (4), the result is 2 .

( In this way, the exact length of the array cannot be obtained . The recommended operation is to calculate the length of the array in the function that defines the array, and pass it out in the form of an actual parameter , so that other functions can obtain the length of the array.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325430500&siteId=291194637