C language learning notes (1): degrades to pointer when an array is passed, and language learning pointer
I wroteArray Element sortingThe function is as follows:
# Include <stdio. h> # include <stdlib. h> void ArraySort (int array []); // sort the array elements from small to large void ArraySort (int array []) {int x, y, tmp; int I = sizeof (array)/4; // obtain the array length as I for (x = 0; x <I; x ++) {for (y = x; y <I; y ++) {if (array [x]> array [y]) {tmp = array [x]; array [x] = array [y]; array [y] = tmp ;}}printf ("Ascending Order:"); for (x = 0; x <I; x ++) {printf ("% d \ t", array [x]) ;}int main (void) {int a [] = {99,66, 6 }; arraySort (a); system ("pause"); return 0 ;}
Check it carefully. If there is no warning and no error, you can sort it. Result:
Why is there only one problem?
The first reaction is that I has a problem, so I checked the value of I:
Why? Int I = sizeof (a)/4; obviously, the length of the array is not obtained successfully,Sizeof (a) Get the memory occupied byte of array a and divide it by the byte occupied by each int (4)It should have been completely correct! WTF? What!
I was dissatisfied, so I wrote another code to test sizeof to get the array length:
# Include <stdio. h> int main (void) {int array [] = {5, 4, 66, 23, 11, 44, 22,361}; int I = sizeof (array)/4; printf ("array length: % d \ n", I); return 0 ;}
This is the result after compilation and running !!!
Obviously, the problem is notSizeofI was thinking about whetherFunction real participation ParameterThere!
Why can it be obtained outside the function ?!
The final result is that I found this:
If you wantPass a single-dimension array as an argument in a function, You wowould have to declare function formal parameter in one of following three ways and all three declaration methods produce similar resultsBecause each tells the compiler That an integer pointer is going to be resolved ed.
Which indicatesWhen passing a one-dimensional array, the compiler does not pass an array, but a pointer!
Okay! I lost in the next step. This article warned me that when I was just learning C language, when passing an array in the function, I should be sure to test the array length outside, otherwise a BUG will occur!