How to count the number of array elements?

The number of array elements we are talking about refers to the total number of elements.
For example:
there are 10 elements in arr[10], there
are 3X4=12 elements in arr[3][4],
so how can we find this number for the computer? ?

For a one-dimensional array

#include <stdio.h>

int main()
{
    
    
	int arr[10] = {
    
     0 };
	int sz = sizeof(arr) / sizeof(arr[0]);

	printf("%d\n", sz);
	return 0;
}

At this time, we calculated the number of elements in this one-dimensional array as follows:! [insert picture description here](https://img-blog.csdnimg.cn/20210124102523489.png

Insert picture description here
For a two-dimensional array

#include <stdio.h>

int main()
{
    
    
	int arr[3][4] = {
    
     0 };
	int sz = sizeof(arr) / sizeof(arr[0][0]);

	printf("%d\n", sz);
	return 0;
}

The results of the program operation are as follows:
Insert picture description here
At this time, let's explain the sz in the above program.
1. First, let us say that for a one-dimensional array, arr[0] represents the first element, and for a two-dimensional array, arr[0][0] represents the first element.
2. Secondly, the array name represents the address of the first element, but there are two exceptions
(1) When sizeof (array name), the array name represents the entire array, not the address of the first element, and sizeof (array name) calculates the entire array size.
(2) In case of & array name (& represents the address character), the array name represents the entire array, and here is the address of the entire array.
In addition, all array names are addresses of the first element.
3. Finally, we use the entire array element to remove the first element of the array to get the number of elements in the array.

Thanks for reading.

Guess you like

Origin blog.csdn.net/JixTlhh/article/details/113071225
Recommended