a few more pointer points
play

A few more pointer points Prints to stdout formatted Beware null - PDF document

int printf(char *fmt, a1 , a2 , ) A few more pointer points Prints to stdout formatted Beware null & wayward pointers! (Learn from Binky) Same as fprintf(stdout, char *fmt, a1, ) Command line arguments Variable


  1. int printf(char *fmt, a1 , a2 , …) A few more pointer points � Prints to stdout – formatted � Beware null & wayward pointers! (Learn from Binky) – Same as fprintf(stdout, char *fmt, a1, …) � Command line arguments – Variable length argument list after format – one for – int main(int argc, char *argv[]) {…} each % in format string (in order) – Equivalent argv declaration: char **argv � % [ - ][width][ . ][precision]character – Either way, argv[i] refers to i th argument – ‘-’ specifies left justification � Pointers to functions – function name is a pointer – width – maximum field width in characters – Can pass to another function as an argument – [.][precision] – for floating point nums only – void other ( int (*func)( func’s parameters ) ) – Character – specific for type to convert � See libqsort.c in ~cs60/demo03 for example � d, i, o, x, u – for integers � Complicated declarations – read from right to left � f, e, g – for floating point – Decipher using K&R’s dcl.c (in ~cs60/demo03) � s for strings, and c for chars Line input and output int scanf(char *fmt, a1 , a2 , …) � Formatted input from stdin � Note: K&R getline is non-standard – better to � For all except %c – skips white space use fgets from <stdio.h> : � Arguments corresponding to conversion char *fgets(char *line, int max, FILE *fp); characters must be pointers: – Reads at most max – 1 characters, including ‘\n’ int x; – The array, line , must be able to hold max chars char word[20]; scanf(“%d %s”, &x, word); � But do not use gets(…) – it’s dangerous – Note – word is already a pointer, so no & � fputs – alternative to fprintf to output lines: – Another note – word array must be large enough int fputs(char *line, FILE *fp); /* returns EOF if error */ � Also sscanf and fscanf – for input from a – Or just use puts(…) for stdout string or a file (i.e., like sprintf and fprintf ) Variable-length argument lists File input/output � #include <stdarg.h> � FILE *fp; /* declare a file pointer */ � va_list ap; � fp = fopen(“filename”, mode ); /* first: declare pointer to unnamed args */ /* associate a file with the pointer */ � va_start(ap, last named-arg ); – mode is char * – either “r” , “w” , or “a” /* aim pointer at first unnamed argument � Input or output using the file pointer: (note: must be at least one named argument) */ – getc(fp); /* returns next int from file */ � type value = va_arg(ap, type ) – putc(intValue, fp); /* outputs value to file */ /* get current unnamed argument, and increment */ � va_end(ap); – fscanf(fp, format, …); /* input from file */ /* must be called when done – before returning */ – fprintf(fp, format, …); /* output to file */ 1

  2. Error handling basics C structures – some basics � Structures are user-defined types with multiple data fields � Do NOT print errors to stdout � e.g., define structure to hold a char and a double : – Print error messages to stderr instead: struct example{ /* type is 2 words: struct example */ char c; fprintf(stderr, “message”, args…); double d; � Often need to terminate execution due to errors }; /* the semicolon is mandatory */ – In main – return EXIT_FAILURE; /* or any non-zero */ � Create a structure, and declare and assign a pointer struct example e, *ep = &e; – In other functions – exit(EXIT_FAILURE); � Or, if won’t need to refer to type name again: � Sometimes want to check error status of file ( fp ) struct { /* can leave off the “tag” */ – General error – ferror(fp); /* returns 0 if no errors */ char c; double d; – End-of-file – feof(fp); /* returns non-0 if end of file */ } e, *ep; More structure basics typedef � Can precede any declaration with typedef � Access fields with the dot ‘ . ’ operator – Defines a name for the given type: – By using the structure’s name: e.d = 2.5; typedef struct example ExampleType; – Or the pointer: (*ep).c = ‘a’; /* parens needed */ ExampleType e, *ep; /* e, ep same as prior slide */ � Easier to use the arrow ‘ -> ’ operator for pointers � Can even use a defined type to define another: – ep->c = ‘a’; typedef ExampleType *ETPointer; � Can initialize all fields in one step: ETPointer ep; /* ep same as above */ – struct example e2 = { ‘c’, 97.14 }; � Note – can simplify code with macros too: � Note – size of structure >= sum of field sizes: #define C(p) (p)->c – sizeof e >= sizeof(char) + sizeof(double) /* preprocessor substitutes correct code */ C(ep) = ‘b’; Structures and functions Collections of structures � Arrays – an alternative to “parallel arrays” � Usually better to pass pointers – avoid copy costs – Mostly handle like all other array types – But gives function access to original fields � ExampleType array[ /*size*/ ], *p; � p = array + 2; /* p points at third struct */ � Note: const not guaranteed in C – See keyword counting programs, K&R p. 134 & 137 � Do not return pointers to local structure variables (today’s demo programs in ~cs60/demo04/) – In this case, accept the copying costs � Linked data structures – a.k.a. self-referential – But okay if dynamically allocate memory for structure typedef struct node { � Returning defined types aids readability: DataType data; struct node *next; /* a pointer to next node */ – ETPointer someFunction() is easy to read } ListNode; – struct example *someFunction() is not – Also see binary search tree program, K&R pp. 140-2 2

  3. Unions More library functions � Can hold different data types/sizes (at different times) � Become familiar with K&R appendix B! � e.g., define union to hold an int or a double : � <string.h> – to deal with char * data union myValue{ � <ctype.h> – to handle individual char s int x; � <math.h> – trig functions, logs, many more double d; – Note: usually must link to libm.a – use -lm } u, *up; /* u is a union, up can point to one */ � Access x or d by u. or up-> just like structures � <stdlib.h> – various utilities � sizeof u is size of largest field in union – Inc. atoi , qsort , rand , malloc , exit , system , … – Equals sizeof(double) in this case � <assert.h> – one cool macro: assert(int) � Often store inside a structure, with a key to identify type � <time.h> , <limits.h> , … – check them out! – Otherwise might be no way to know which field to access 3

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend