Download presentation
Presentation is loading. Please wait.
Published byGeraldine Randall Modified over 9 years ago
1
Pointer Arithmetic (1) u When a pointer variable points to an array element, there is a meaning of adding or substracting an integer to/from the pointer. int a[10], *p, *q; p = &a[2]; q = p + 3; /* q points to a[5] now */ p = q – 1; /* p points to a[4] now */ p++; /* p points to a[5] now */ p--; /* p points to a[4] now */ *p = 123; /* a[4] = 123 */ *q = *p; /* a[5] = a[4] */ q = p; /* q points to a[4] now */ scanf(“%d”, q) /* scanf(“%d”, &a[4]) */
2
Pointer Arithmetic (2) u If two pointers point to elements of a same array, then there are meanings of subtraction and comparisons between the two pointers. int a[10], *p, *q, i; p = &a[2]; q = &a[5]; i = q - p; /* i is 3*/ i = p - q; /* i is -3 */ a[2] = a[5] = 0; i = *p - *q; /* i = a[2] – a[5] */ p < q; /* true */ p == q; /* false */ p != q; /* true */ p > q; /* false */
3
Array name is like a constant pointer u Array name is like a constant pointer which points to the first element of the array. int a[10], *p, *q; p = a;/* p = &a[0] */ q = a + 3; /* q = &a[0] + 3 */ a ++; /* illegal !!! */ u Therefore, when you passing an array as an argument, the value of the constant pointer is passed. That is, the address of the array is passed. void sort(int ary[ ], int size); int main( ) { int a[ ] = { 5, 7, 8, 2, 3}; sort( a, 5 ); ……….
4
An example – BinSearch /* binary search – suppose ary is sorted in descending order; return whether key is in ary*/ int BinSearch(int * ary, int size, int key) { int i; if(size < 1) return 0; else if(size==1) return ary[0] == key; else{ i = size/2; if( ary[i] < key) return BinSearch( ary, i, key ); else if ( ary[i] > key ) BinSearch( ary + i + 1, size – i -1, key ); else return 1; } } /* this is not the best implementation of Binary Search. */
5
Allocate memory for a pointer (1) u The following program is wrong! #include int main() { int *p; scanf(“%d”,p); return 0; } u We use the following program insteadly: #include int main() { int *p; int a; p = &a; scanf(“%d”,p); return 0; }
6
Allocate memory for a pointer (2) u We can also use the following code: #include int main() { int *p; p = (int *) malloc( sizeof(int) ); /*allocate 4 bytes*/ scanf(“%d”, p); printf(“%d”, *p); free(p);/* this returns the memory to the system */ /* Important !!! */ }
7
Allocate memory for a pointer (3) u Prototypes of malloc() and free() are defined in stdlib.h void * malloc(size_t number_of_bytes); void free(void * p); u You can use malloc and free to dynamically allocate and release the memory; { /* the following code is just for demo*/ int *p; p = (int *) malloc(1000 * sizeof(int) ); for(i=0;i<1000;i++) { p[i] = i; } …… free(p); }
8
An example – finding the prime numbers /* print out all prime numbers which are less than m */ int print_prime( int m ) { int i,j; char * ary; ary = malloc( m ); if(ary==NULL) return -1; ary[0]=ary[1]=0; ary[2]=1; for(i=3;i<m;i++) { ary[ i ] = 1; for( j=2; j<i; j++) { if( ary[ j ] ) /* j is prime */ if( i % j == 0) ary[j]=0; } for(i=0;i<m;i++) if(ary[i]) printf(“%d “, i); free( ary ); return 0; }
9
Strings
10
Strings are char arrays u Strings in C are simply arrays of characters –Example: char str [10]; u This is a ten (10) element array that can hold a character string consisting of up to nine (9) characters u This is because C does not know where the end of an array is at run time –by convention C uses a null character `\0` to terminate all strings in its library functions u For Example: char str [10] = {`W`, `i`, `n`, `n`, `i`, `p`, `e`, `g`, `\0`}; v is equivalent to char str [10] = “Winnipeg”; u Always remember that string terminator!
11
Printing with printf ( ) u Example: char str[ ] = “A message to display”; printf (“%s\n”, str); u printf expects to receive a char* to that string with the %s conversion specifier –since an array name is like a constant pointer it works fine u The following code is wrong: printf (“%s”, *str); –*str is str[0], which is a character (between 0 and 255) –%s expects a pointer, so type conversion occurs –printf will think that you want to print the string which begins at the k-th byte of the memory, where 0 <= k <= 255 is the value of str[0] u Another common error is to forget the \0 terminator –this will print out some junks until a byte 0 is encountered
12
Printing with puts( ) u The puts function is a much simpler print instruction u Prototype of puts is defined in stdio.h int puts(const char * str) –This is more efficient than printf v don't need to analyze the format string at run-time u For Example: char *sentence = "The quick brown fox\n"; puts(sentence); u prints out The quick brown fox
13
Entering strings with gets u gets( ) gets a line from the standard input. u The prototype is defined in stdio.h char *gets(char *str) –The parameter str is a pointer to the space where gets will store the line to. –The return value is NULL upon failure. Otherwise, it returns str. { char your_line[100]; printf(“enter a line:\n”); gets(your_line); puts(“your input follows\n”); puts(your_line); }
14
What’s wrong with the following code #include int main() { char *your_line; puts(“input a line:”); gets(your_line); puts(your_line); }
15
Two methods to fix the above program u 1. Using an array instead of the pointer char your_line[100]; puts(“input a line:”); gets(your_line); u 2. Allocate some memory for the pointer #include “stdlib.h” #include “stdio.h” int main() { char *your_line; your_line = (char *) malloc ( 100 ); gets(your_line); puts(your_line); free(your_line); }
16
Inputting Strings with scanf ( ) u Uses the same format string as usual u To read a string include: –%s scans up to but not including the “next” whitespace character –%ns scans the next n characters or up to the next white space character, whichever comes first u Example: scanf (“%s%s%s”, s1, s2, s3); scanf (“%2s%2s%2s”, s1, s2, s3); u Difference between gets –gets( ) read a line –scanf(“%s”,…) read up to the next space
17
An Example #include int main () { char lname[81], fname[81]; int count, id_num; puts ("Enter the last name, firstname, ID number separated"); puts ("by spaces, then press Enter"); count = scanf ("%s%s%d", lname, fname, &id_num); printf ("%d items entered: %s %s %d", count,fname,lname,id_num); return 0; }
18
The C string library u As we have seen, strings are simply pointers to chars –there is a convention that the last character is null (‘\0’) –there is very little language support in C for strings u String functions are provided in an ANSI standard string library –access this through the include file #include –includes functions for v computing length of string v copying strings v concatenating strings –this library is guaranteed to be there in any ANSI standard implementation of C
19
strlen u Strlen returns the length of a NULL terminated character string size_t strlen (char * str) ; u Defined in string.h u size_t –a type defined in string.h that is equivalent to an unsigned int u char *str –points to a series of characters ending with ‘\0’ –The following code has a problem! char a[5]={‘a’, ’b’, ’c’, ’d’, ’e’}; strlen(a);
20
Copying Strings (1) u Copying a string comes in three forms char *strcpy (char * destination, char * source); v in string.h a copy of * source is made at * destination –* source should be NULL terminated v the return value also points at the destination char *strncpy (char *destination, char *source, size_t n); v returns a destination string n characters long v if source < n the destination is padded with NULLs v if source is > n the destination is n long and NOT NULL terminated
21
Copying Strings (2) u An Example: strcpy #include int main() { char dest1[80], *dest2, *dest3; char source [] = "The source string."; printf ("\nSource: %s", source); strcpy (dest1, source); printf ("\nDest1: %s", dest1); dest2 = malloc(strlen(source) + 1); strcpy (dest2, source); printf ("\nDest2: %s", dest2); /* strcpy (dest3, source); fails Why? */ }
22
Copying Strings (3) u An Example: strncpy int main() { size_t n; char dest [] = ".........................."; char source [] = "abcdefghijklmnopqrstuvwxyz"; while (1) { puts ("Enter the number of chars to copy (1-26)"); scanf ("%d", &n); if (n>0 && n<27) break; } printf ("\nBefore strncpy destination = %s", dest); strncpy (dest, source, n); printf ("\nAfter strncpy destination = %s", dest); return 0; }
23
Concatenating Strings (1) u included in string.h and comes in two forms char * strcat (char * str1, char * str2); v appends a copy of *str2 to the end of *str1 v a pointer equal to str1 is returned char * strncat (char * str1, char * str2, size_t n); v if str2 > n chars then only n chars are appended v if str2 < n chars then all of str2 is appended v in both cases the string is terminated with a NULL u always ensure that str1 has sufficient space for the concatenated string –Array index out of range will be the most popular bug in your programming career.
24
Concatenating Strings (2) u An Example - strcat #include int main() { char str1[27] = "a"; char str2[2] ; char n; str2[1] = '\0'; for (n=‘b’;n<=‘z’;n++) { str2[0] = n; strcat(str1,str2); puts (str1); }
25
Comparing Strings (1) u C strings can be compared for equality or inequality u If they are not equal then C will inform you –“How they are unequal.” u If they are equal - they are ASCII identical u If they are unequal the comparison function will return an int that is interpreted as: < 0 : str1 is less than str2 0 : str1 is equal to str2 > 0 : str1 is greater than str2
26
Comparing Strings (2) u Two basic comparison functions int strcmp (char *str1, char *str2) ; v does an ASCII comparison one char at a time until a difference is found between two chars –return value is as stated before v if both string reach a ‘\0’ at the same time they are equal int strncmp (char *str1, char * str2, size_t n); v compares n chars of str1 and str2 –continues until n chars compared or –the end of str1or str2 encountered
27
Comparing Strings (3) u An Example - strcmp int main() { char str1[80], str2[80]; int x; while (1) { printf ("\n\nInput the first string, blank out: "); gets (str1); if (strlen(str1)==0) break; printf ("\nInput the second string: "); gets (str2); x = strcmp(str1,str2); printf ("\nstrcmp(%s,%s) returns %d", str1,str2,x); }
28
Comparing Strings (4) u An Example - strncmp int main() { char str1[] = "The first string."; char str2[] = "The second string."; size_t n,x; puts (str1); puts (str2); while (1) { printf ("\n\nEnter the num of chars to compare, 0 out."); scanf ("%d", &n); if (n <= 0) break; x = strncmp(str1,str2,n); printf ("\nstrncmp for %d chars returns %d",n,x); }
29
Searching Strings (1) u There are a number of u There are a total of six of these –char * strchr (char * str, int ch) ; v strchr search * str until ch is found or NULL v if found a pointer to ch is returned –else return NULL –you determine its location (index) in the string by v subtracting the value returned from the address of the start of the string –more pointer arithmetic
30
Searching Strings (2) Example use of strchr: int main() { char *loc, buf[80]; int ch; printf ("Enter the string to be searched: "); gets (buf); printf ("Enter the character to search for: "); ch = getchar(); loc = strchr (buf,ch); if (loc == NULL) printf ("The character %c was not found.",ch); else printf ("The character %c was found at position %d", ch, loc-buf+1); }
31
Search Strings (3) char * strrchr (char *str, int ch); v searches for the last occurrence of a character v returns a pointer to the last a NULL if not found size_t strcspn (char * str1, char * str2) ; v searches *str1 looking for any character in *str2 v if found it returns offset from beginning of str1 v if not found it returns strlen (str1) –i.e. it matched at the NULL character of str1 size_t strspn (char * str1, char * str2); v returns position of first char in str1 NOT matching a char in str2 v in short, it returns the length of the initial segment of str1 that consists entirely of chars found in str2 char * strpbrk (char * str1, char * str2); v same as strcspn but does not include the NULL character v if it fails to find a match it returns NULL else a pointer char* strtok(char* s, const char* t); v A sequence of calls to strtok returns tokens from s delimted by a character in ct. v Non-NULL s indicates the first call in a sequence. ct may differ on each call. Returns NULL when no such token found.
32
Searching Strings (4) The strstr function int main() { char *loc, buf1[80], buf2[80]; printf ("Enter the string to be searched: "); gets (buf1); printf ("Enter the target string: "); gets (buf2); loc = strstr (buf1,buf2); /* search for string buf2 in string buf1 */ /* returns a pointer to string if found, NULL o/w */ if (loc == NULL) printf ("No match was found."); else printf ("%s was found at position %d", buf2, loc-buf1+1); }
33
Converting Strings to Numbers (1) u Contained in and are often used int atoi (char *ptr); –takes a character string and converts it to an integer –whitespace and + or - are OK –starts at beginning and continues until something non-convertible is encountered v for example : “!” u Some examples: String Value returned “157”157 “-1.6”-1 “+50x”50 “twelve”0 “x506”0
34
Converting Strings to Numbers (2) long atol (char *ptr) ; –same as atoi except it returns a long and can handle larger integer numbers double atof (char * str); –handles digits 0-9 –a decimal point –an exponent indicator (e or E) –if no characters are convertible a 0 is returned u Examples: –StringValue returned “12”12.000000 “-0.123”-0.123000 “123E+3”123000.000000 “123.1e-5”0.001231
35
Converting Strings to Numbers (3) Example: #include int main() { char buf[80]; double d; while (1) { printf ("\Enter string to convert, blank out: "); gets (buf); if (strlen(buf)==0) break; d = atof (buf); printf ("The converted value is %f.\n", d); }
36
sprintf u Sometime, you want to print something not to your stdout, but a string in your program. You can use sprintf. u The prototype is defined in stdio.h int sprintf( char *s, const char *format, …); u Example: #include int main() { char result[100]; sprintf(result, “%f”, (float)17/37 ); if( strstr(result, “45”) != NULL ) printf(“the digit sequence 45 is in 17 over 37. \n”); return 0; }
37
Structures
38
Structures (1) u Structures are C’s way of grouping collections of data into a single manageable unit –This is also the fundamental element of C upon which most of C++ is built (i.e., classes) –similar to Java's classes u An Example: –defining a structure type struct coord { int x ; int y ; }; –this defines a new type coord. No variable is generated.
39
Structures (2) u Define struct variables: –An Example: struct coord { int x ; int y ; } first, second; u Another Approach: struct coord { int x ; int y ; };............... struct coord first, second; /* declare struct variables */ struct coord third; Declare variables of type "struct coord" note: you need the word struct
40
Structures (3) u You can even use a typedef if your don't like the word "struct" typedef struct coord coordinate; coordinate first, second; u In some compilers and all C++ compilers, you can simply coord first, second;
41
Structures (4) u Access structure variables by the dot (.) operator u Generic Form structure_var. member_name u For Example: first.x = 50 ; second.y = 100; u These member names, accessed through the dot operator, can be used anywhere a variable of the member type can be used –Very similar to Java & C++ with data members –There is no equivalent to function members/methods in C u E.g. –printf (“%d, %d”, second.x, second.y ); –scanf(“%d, %d”, &first.x, &first.y);
42
Structures (5) u You can assign structures as a unit with = u For example first = second; instead of first.x = second.x ; first.y = second.y : u Although the saving here is not great –it will reduce the likelihood of errors and –is more convenient with large structures u Much more necessary in C++ u This is different from Java where variables are simply references (essentially pointers) to objects first = second; makes first and second refer to the same object –the C semantics is more like first = second.clone(); /* in Java */
43
Structures Containing Structures u Essentially any “type” of thing can be a member of a structure u We can use the coord struct to define a rectangle struct rectangle { struct coord topleft; struct coord bottomrt; } ; u This describes a rectangle by using the two points necessary struct rectangle mybox ; u Initializing the points is: mybox.topleft.x = 0 ; mybox.topleft.y = 10 ; mybox.bottomrt.x = 100 ; mybox.bottomrt.y = 200 :
44
An Example #include struct coord { int x; int y; }; struct rectangle { struct coord topleft; struct coord bottomrt; }; int main () { int length, width; long area; struct rectangle mybox; printf("Enter top left x coord: "); scanf("%d", &mybox.topleft.x); printf("\nEnter top left y coord: "); scanf("%d", &mybox.topleft.y); printf("\nEnter bottom right x coord: "); scanf("%d", &mybox.bottomrt.x); printf("\nEnter bottom right x coord: "); scanf("%d", &mybox.bottomrt.y); width = mybox.bottomrt.x – mybox.topleft.x; length = mybox.bottomrt.y – mybox.topleft.y; area = width * length; printf ("The area is %ld units.", area); }
45
Structures Containing Arrays u Arrays within structures are the same as any other member element u For example: struct record { float x; char y [5] ; } ; u Logical Organization: floatchar[5] record
46
An Example #include struct data { float amount; char fname[30]; char lname[30]; } rec; int main () { struct data rec; printf ("Enter the donor's first and last names, \n"); printf ("separated by a space: "); scanf ("%s %s", rec.fname, rec.lname); printf ("\nEnter the donation amount: "); scanf ("%f", &rec.amount); printf ("\nDonor %s %s gave $%.2f.", rec.fname,rec.lname,rec.amount); }
47
Arrays of Structures u The converse of a structure with arrays u Example: struct entry { char fname [10] ; char lname [12] ; char phone [8] ; } ; struct entry list [1000]; u This creates a list of 1000 identical entry(s) u Assignment: list [1] = list [6]; strcpy (list[1].phone, list[6].phone); list[6].phone[1] = list[3].phone[4] ;
48
An Example #include struct entry { char fname [20]; char lname [20]; char phone [10]; } ; int main() { struct entry list[4]; int i; for (i=0; i < 4; i++) { printf ("\nEnter first name: "); scanf ("%s", list[i].fname); printf ("Enter last name: "); scanf ("%s", list[i].lname); printf ("Enter phone in 123-4567 format: "); scanf ("%s", list[i].phone); } printf ("\n\n"); for (i=0; i < 4; i++) { printf ("Name: %s %s", list[i].fname, list[i].lname); printf ("\t\tPhone: %s\n", list[i].phone); }
49
Initializing Structures u Simple Example: struct sale { char customer [20] ; char item [20] ; float amount ; }; struct sale mysale = { “Acme Industries”, “Zorgle blaster”, 1000.00 } ;
50
Initializing Structures u Structures within Structures struct customer { char firm [20] ; char contact [25] ; }; struct sale { struct customer buyer ; char item [20] ; float amount ; } mysale = { { “Acme Industries”, “George Adams”}, “Zorgle Blaster”, 1000.00 } ;
51
Initializing Structures u Arrays of Structures struct customer { char firm [20] ; char contact [25] ; } ; struct sale { struct customer buyer ; char item {20] ; float amount ; } ; struct sale y1990 [100] = { { { “Acme Industries”, “George Adams”}, “Left-handed Idiots”, 1000.00 } { { “Wilson & Co.”, “Ed Wilson”}, “Thingamabob”, 290.00 } } ;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.