<>C Some thoughts on the length calculation of array passed by parameter in language
<> One background
study C In the process of language , Calculating the length of an array often encounters . In character arrays, we can use strlen()
To get the length of the current array , For other types of arrays , This method doesn't work . Because we often encounter the problem of calculating array length , After thinking , Consider the calculation of array length by a function . This is the idea : Passing an array to a length function by a parameter , Length calculation function returns array length after calculation . But there are some problems in practice , Please keep looking down !
<> Two Implementation code
Based on the above ideas , Write the following paragraph demo:
# include<stdio.h> int main(int argc, char * argv[]) { int a[] = {2, 6, 3, 5, 9
}; // int length(int *); int length(int []); printf("The length of this array
is: %d\n",length(a)); printf("The length of this array is: %d\n",sizeof a /
sizeof a[0]); return 0; } // int length(int *a) int length(int a[]) { int length
; length = sizeof a / sizeof a[0]; return length; }
results of enforcement :
The length of this array is: 2 The length of this array is: 5
<> Three Result analysis and summary
*
3.1 First result , Calculate the length of an array by passing parameters to the array length calculation function , The result is : 2. Obviously , This is a wrong result .
*
3.2 Second result , Calculate array length directly , Meet expectations .
*
3.3 Access to relevant information , The following conclusions are drawn :
a[] Is the formal parameter of length calculation , stay main() Invocation time in function ,a Is a pointer to the first element of the array . In execution main() Function time , hear nothing of a
How much data storage space does the address represent , Just tell the function : First address of a data storage space .
sizeof a The result is a pointer variable a Size of memory , Generally in 64 On the plane 8 Bytes .a[0] yes int type ,sizeof a[0]
yes 4 Bytes , The result is 2. to this end , Let's take a look at the following code :
# include<stdio.h> int main(int argc, char * argv[]) { int a[] = {2, 6, 3, 5, 9
}; // int length(int *); int length(int []); int *p; p = a; printf("The length
of this array is: %d\n", length(a)); printf("The length of this array is: %d\n",
sizeof a /sizeof a[0]); printf("The length of this pointer is: %d\n", sizeof p);
return 0; } // int length(int *a) int length(int a[]) { int length; length =
sizeof a / sizeof a[0]; return length; }
results of enforcement :
The length of this array is: 2 The length of this array is: 5 The length of
this pointer is: 8
Technology
Daily Recommendation