Sizeof in C language and sizeof in C Language
Today, I want to use C to implement a half-fold search of arrays. The original algorithm was quite simple, but it took several hours to find out where the problem was. This sizeof trap is not a problem.
1 # include <stdio. h> 2 void m (int []); 3 int main () {4 int a [9] = {1, 2, 4, 5, 6, 7, 8, 9 }; 5 printf ("% d \ n", sizeof (a); 6 m (a); 7 8 return 0; 9} 10 11 void m (int k []) {12 printf ("% d \ n", sizeof (k); 13 14}
The result of the first row is 39, and the result of the second row is 4. Why is the result of the same Array different? The reason is that it occurs in sizeof. This is because sizeof is an operator, mistaken for a function, and that the original meaning of the array has been lost during the transfer process. In m function, it is actually an array pointer passed, therefore, 12th rows are actually the size of the pointer to be tested.
See here. refer to the previous C code to achieve half-fold.
1 # include <stdio. h> 2 int binearySearch (int [], int, int); 3 int main () {4 int a [9] = {1, 2, 3, 4, 5, 6, 7, 8, 9 }; 5 int m = 5; 6 int length = sizeof (a)/sizeof (int); 7 int s = binearySearch (a, length, m ); 8 if (s = 0) 9 printf ("not found! \ N "); 10 else11 printf (" % d \ n ", s); 12 return 0; 13} 14 15 int binearySearch (int m [], int N, int k) {16 int start, end, middle; 17 start = 0; 18 end = N; 19 while (start <end) {20 middle = (start + end) /2; 21 if (m [middle] = k) {22 return middle + 1; 23} 24 else if (m [middle]> k) {25 end = middle; 26} 27 else if (m [middle] <k) {28 start = middle; 29} 30} 31 return 0; 32}
The above result is 5.