Pointers in C - (H& K chapter 7)
4 flashcards · Programming Languages · by sky bear
Pitfalls of pointers and output parameters
Not assigning the pointer a valid memory address Improper use of the deference or indirection operator *ptr = &variable ; // likely incorrect ptr = variable ; // should be *ptr = number Overusing pointers - making a function compute too many results deviates from proper top - down design Overcomplicating pointers (it's just a variable ☺)
Example problem: prompts the reader for a date string in the form { mm/dd/yyyy }. The function should return a valid month, day, and year as output parameters. (answer in pseudocode)
Algorithm Pseudocode for "get_date" (Set valid to true) Do{ printf ('enter date string "); scan date string into month, seperator1, day, separator2, year; if{ (status of scan is not equal to 5) or (separator1 is not a '/') or (separator2 is not a '/') or (day <0) or (day > 31) or (month < 1) or (month > 12) or (year < 0) } set valid to false printf("date string is invalid"); end if ; while not valid return day, month, year End get_date
void get_date(int *month, int *day, int *year){} (write the function)
void get_date(int *month, int *day, int *year) { int valid, status; char sep1, sep 2; do { valid = 1; printf ("Please enter a date (mm/dd/yyyy) \n"); status = scanf(" %d, %c%d %c%d", month, &sep1, day, &sep2, year); if (status < 5 || sep1 != '/' || sep2 != '/' || *day < 0 || *day > 31 || *month < 1 || *month < 12 || *year < 0 || *year > 9999) { valid = 0; printf (" The string date you entered isn't valid. \n"); } } while !valid; }
When you're not sure what functions are needed:
Need for a specific function is not always clear in advance [ For example, the day_diff_within_year {} and days_in_month {} functions were not included in my preliminary top-down design – Do not feel obligated to write out every function! ] A "stub" that displays a text message can be useful initially; refine gradually – Do not be afraid to use the debugger