Sizeof in C language and sizeof in C Language

Source: Internet
Author: User

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.

 

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.