Chapter 3 C traps and Defects

Source: Internet
Author: User

Exercise 3.1 assumes that the array element whose subscript is out of bounds is invalid even if the address is obtained, how should the bufwrite program in section 3.6 of the book be written?

The source program in section 3.6 is:

void bufwrite(char *p,int n){     while(n > 0){          int k,rem;          if(bufptr == &buffer[N])               flushbuffer();          rem = N - (bufptr - buffer);          k = n > rem ? rem : n;          memcpy(bufptr,p,k);            bufptr += k;          p += k;          n -= k;     }}

According to your own ideas

if(bufptr == &buffer[N])

Change to the following statement:

if(bufptr > &buffer[N - 1])

Practice 3.2I personally think that the flush function in the exercise will be less efficient and will be compared more steps.

Exercise 3.3 compile a function to perform a binary search for a sorted integer table. Function input includes a pointer to the header, the number of elements in the table, and the value to be searched. The function output is a pointer to elements that meet the search requirements. If no value that meets the requirements is found, a null pointer is output.

The program is as follows:

int *FindNum(int *pTab,int TolNum,int FindNum){     int low = 0,high = TolNum - 1,mid = 0;     if(pTab[low] == FindNum){          return pTab;     }     if(pTab[high] == FindNum){          pTab = pTab + high;          return pTab;     }     while(low <= high){          mid = ((high - low) / 2) + low;          if(pTab[mid] == FindNum){               pTab = pTab + mid;               return pTab;          }          else{               if(pTab[mid] > FindNum)                    high = mid - 1;               else                    low = mid + 1;          }     }     return NULL;}

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.