More Pointers and Arrays Kernighan/Ritchie: Kelley/Pohl: Chapter 5 Chapter 6.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
Strings.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Ch 8. Characters and Strings Timothy Budd 2 Characters and Literals Strings Char in C++ is normally an 8-bit quantity, whereas in Java it is a 16-bit.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
Elementary Data Structures: Part 2: Strings, 2D Arrays, Graphs
Pointers in C Rohit Khokher
Programming in C Pointers and Arrays, malloc( ). 7/28/092 Dynamic memory In Java, objects are created on the heap using reference variables and the new.
Kernighan/Ritchie: Kelley/Pohl:
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Programming C/C++ on Eclipe Trình bày : Ths HungNM C/C++ Training.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 8 - Characters and Strings Outline 8.1Introduction.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
CSSE221: Software Dev. Honors Day 28 Announcements Announcements Simulation grades coming back Simulation grades coming back All C Projects due Friday.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
CS 201 String Debzani Deb.
Chapter 8 Arrays and Strings
 2007 Pearson Education, Inc. All rights reserved C Characters and Strings.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
EPSII 59:006 Spring Introduction Fundamentals of Strings and Characters Character Handling Library String Conversion Functions Standard Input/Output.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
February 14, 2005 Characters, Strings and the String Class.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Arrays and Pointers.
UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.
Characters and Strings
Multi-dimensional Arrays and other Array Oddities Rudra Dutta CSC Spring 2007, Section 001.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
19-Feb-02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Arrays, Pointers, Strings Lecture 18 19/2/2002.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 5 : September 4.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
Windows Programming Lecture 03. Pointers and Arrays.
Computer Organization and Design Pointers, Arrays and Strings in C
C Characters and Strings
C Programming Tutorial – Part I
Arrays in C.
Chapter 8 - Characters and Strings
7 Arrays.
Arrays, Pointers, and Strings
Pointers.
Presentation transcript:

More Pointers and Arrays Kernighan/Ritchie: Kelley/Pohl: Chapter 5 Chapter 6

222 Lecture Overview  Strings and characters  String functions in the standard library  sizeof Revisited  Multidimensional arrays  Pointers to pointers and pointer arrays  Pointers to functions

333 Strings  As we have seen before, strings in C are one- dimensional arrays of type char  By convention, strings end with a ' \0 ', thus memory allocated to hold a string should include one additional space  A string constant is treated by the compiler as a pointer to the string's base address

444 Strings  p can be used like any other pointer:  To further emphasize this point: Note that such code should never be used in any real program! char *p = "abc"; printf ("%s %s\n", p, p + 1); abc bc printf ("%c %c\n", "abc"[1], *("abc" + 2)); b c

555 The Character Type Library  The library ctype.h provides macros to check whether a character belongs to a certain character class  Some examples: isspace – Checks for white-space isalpha – Checks for an alphabetic character isdigit – Checks for a digit (0 through 9) islower – Checks for a lower-case character

666 Example – Counting Words in a String #include int count_words (char *s) { int cnt = 0; while (*s != '\0') { while (isspace (*s)) /* skip white space */ s++; if (*s != '\0') { /* found a word */ cnt++; while (!isspace (*s) && *s != '\0') s++; /* skip the word */ } return cnt; }

777 The Character Type Library – Complete List MacroReturns true if: int isalpha (int c); int isupper (int c); int islower (int c); int isdigit (int c); int isalnum (int c); int isxdigit (int c); int isspace (int c); int ispunct (int c); int isprint (int c); int isgraph (int c); int iscntrl (int c); int isascii (int c); c is a letter c is an uppercase letter c is a lowercase letter c is a digit c is a letter or digit c is a hexadecimal digit c is a white space character c is a punctuation character c is a printable character c is printable, but not a space c is a control character c is an ASCII code

888 Lecture Overview  Strings and characters  String functions in the standard library  sizeof Revisited  Multidimensional arrays  Pointers to pointers and pointer arrays  Pointers to functions

999 String Functions in the Standard C Library  The standard C library provides several functions for handling strings  The function prototypes for string handling functions are given in the standard header file string.h  Functions are available for comparing, copying or concatenating strings

10 String Functions in the Standard Library  All string functions take arguments and return values of type char *  Some of the parameters also include the const qualifier, which means: The characters pointed to cannot be changed The pointer itself can be changed  Allocating enough memory to store the results is the responsibility of the caller

11 String Concatenation  This function takes two strings as arguments, concatenates them, and puts the result in s1  The programmer must ensure that s1 points to enough space to hold the result  The string s1 is returned char *strcat (char *s1, const char *s2);

12 String Comparison  The strings are passed as arguments, and neither one is changed by the function  An integer is returned that is less than, equal to, or greater than zero, depending on whether s1 is lexicographically less than, equal to, or greater than s2 int strcmp (const char *s1, const char *s2);

13 String Copy  The string s2 is copied into s1 until (and including) the character ' \0 '  Whatever exists in s1 is overwritten  It is assumed that s1 has enough space to hold the result  The value s1 is returned char *strcpy (char *s1, const char *s2);

14 String Copy  The strdup() function returns a pointer to a new string which is a duplicate of the input string s  Memory for the new string is obtained with malloc(), and can be freed with free() char *strdup (const char *s);

15 String Length  This function simply counts the number of characters in the string  The character ' \0 ' is not included in the count  Note that in C the size of the string is not kept, and must be recomputed every time size_t strlen (const char *s);

16 Finding a Character within a String char *strchr (const char *s, int c);  Looks for the first occurrence of the character c inside the string s  Returns a pointer to the position in the string where c was found  Returns NULL if c was not found

17 Finding a Sub-string within a String  Looks for the first occurrence of the sub-string s2 inside the string s1  Returns a pointer to the beginning of s2 within s1  Returns NULL if s2 was not found char *strstr (const char *s1, const char *s2);

18 Example – String Functions #include int main() { char *question = "Do you want to understand?"; char answer[80], *q_mark, *you; strcpy (answer, "If "); you = strstr (question, "you"); strcat (answer, you); q_mark = strchr (answer, '?'); strcpy (q_mark, " something,\ntry to change it."); printf ("%s\n", answer); } If you want to understand something, try to change it.

19 Lecture Overview  Strings and characters  String functions in the standard library  sizeof Revisited  Multidimensional arrays  Pointers to pointers and pointer arrays  Pointers to functions

20 sizeof Revisited  As we have seen, the sizeof operator can be applied to variables or to types  sizeof can also be applied to arrays  In this case, it returns the size of the memory occupied by the complete array  This only works for static arrays – will not work for pointers

21 sizeof String – Example #include int main() { char *question = "Do you want to understand?"; char answer[80]; printf ("question size: %d\n", sizeof (question)); printf ("answer size: %d\n", sizeof (answer)); return 0; } Size of question: 4 Size of answer: 80

22 sizeof Example Explained  sizeof is a compile-time operator  It cannot know in advance where question will point to during run-time  answer is an array, which is essentially a constant pointer to static memory  Therefore, answer will always point to the same 80 character memory block

23 sizeof Array – Example 1 int main() { int a[] = {12, 32, 434, 43, 26, 873, 43}; int array_size = sizeof (a) / sizeof (int); int i; printf ("Size of a: %d\n", sizeof (a)); for (i = 0; i < array_size; i++) printf ("%d ", a[i]); printf ("\n"); } Size of a:

24 sizeof Array – Example 2 int main() { double a[] = {12, 32, 434, 43, 26, 873, 43}; int array_size = sizeof (a) / sizeof (int); int i; printf ("Size of a: %d\n", sizeof (a)); for (i = 0; i < array_size; i++) printf ("%.0f ", a[i]); printf ("\n"); } Size of a: Wrong!

25 sizeof Array – Example 3 int main() { double a[] = {12, 32, 434, 43, 26, 873, 43}; int array_size = sizeof (a) / sizeof (a[0]); int i; printf ("Size of a: %d\n", sizeof (a)); for (i = 0; i < array_size; i++) printf ("%.0f ", a[i]); printf ("\n"); } Size of a:

26 Lecture Overview  Strings and characters  String functions in the standard library  sizeof Revisited  Multidimensional arrays  Pointers to pointers and pointer arrays  Pointers to functions

27 Multidimensional Arrays  The C language allows arrays of any type, including arrays of arrays  With two bracket pairs, we can obtain a two- dimensional array  This idea can be iterated to obtain arrays of higher dimension int a[100]; /* a one-demensional array */ int b[2][7]; /* a two-dimensional array */ int c[5][3][2]; /* a three-dimensional array */

28 Two-dimensional Arrays  Elements of a two dimensional array are stored contiguously one after the other  However, it is convenient to think of the array as having rows and columns  To define an array with 3 rows and 5 columns: int a[3][5];

29 Two-dimensional Array Initialization  Like simple arrays, multidimensional arrays can be initialized with a list of literals: int main() { int array[3][5] = { { 1, 3, 5, 7, 9 }, { 11, 13, 15, 17, 19 }, { 21, 23, 25, 27, 29 } }; printf ("sum: %d\n", sum (array)); return 0; } sum: 225

30 Two-dimensional Arrays – Formal Parameter Declaration  The compiler only needs to know the number of elements in each row, so the parameter could be defined as either of: int sum (int a[3][5]) { int i, j, sum = 0; for (i = 0; i < 3; ++i) for (j = 0; j < 5; ++j) sum += a[i][j]; return sum; } int a[][5]int (*a)[5]int a[3][5]

31 Two-dimensional Array Access  To access an element in the array, we use:  The following expressions are equivalent: *(a[i] + j) a[i][j] (*(a + i))[j] *((*(a + i)) + j) *(&a[0][0] + 5*i + j)

32 Two-dimensional Array Access – Example a[0][0] a[1][2] *(a[2] + 1) *a[1] *(a[0] + 12) (*(a + 1))[4] *(&a[0][0] + 5*2 + 4)

33 Two-dimensional Array Access – Example  a is an array of size 3  Each element of a is an array of size 5 For example, a[1] is an array of 5 integers  a[1]+2 moves two integers (or 8 bytes) forward – the result is an array of integers  a+2 moves 10 integers forward, since each element of a is an array of 5 integers

34 Lecture Overview  Strings and characters  String functions in the standard library  sizeof Revisited  Multidimensional arrays  Pointers to pointers and pointer arrays  Pointers to functions

35 Pointers to Pointers  In C, pointers are just another type of variables  Therefore, they can be stored in arrays, or pointed to by other pointers  A pointer which points to another pointer will have a special type, such as: int **ppi;

36 Pointers to Pointers – Example  When we wanted to swap between two variables, we used pointers  Similarly, when we want to swap between pointers, we will need pointers to pointers: void swap_char_ptrs (char **ppx, char **ppy) { char *tmp; tmp = *ppx; *ppx = *ppy; *ppy = tmp; }

37 Pointers to Pointers – Example int main() { char *first = "Hello, world!\n"; char *second = "Goodbye, world...\n"; swap_char_ptrs (&first, &second); printf (first); printf (second); return 0; } Goodbye, world... Hello, world!

38 Pointer Arrays  The array used in the sum example could have been defined as a pointer array: b[0] b[1] b[2]

39 Pointer Arrays Compared to Multidimensional Arrays  The syntax of C may cause some confusion between a two-dimensional array and an array of pointers  Both a[1][2] and b[1][2] are syntactically legal references to a memory location of type int int a[3][5]; int *b[3];

40 Pointer Arrays Compared to Multidimensional Arrays  The definition of a allocates 15 int -sized memory locations The space of any unused array slots is wasted  The definition of b only allocates 3 pointers, which should be initialized The space allocated for the pointers themselves is wasted, but the (larger) space for array slots can be accurately allocated

41 Ragged Arrays  A ragged array is an array of pointers used as a two-dimensional array  Requires allocating memory for each row  Advantages: Can save space when row sizes differ Makes it possible to operate on complete rows, and not only on individual cells

42 Ragged Arrays – Example int main() { char in_word[MAX_WORD_LEN]; char *words[MAX_WORDS]; int len, cnt = 0; while (scanf ("%s", in_word) == 1) { len = strlen (in_word); words[cnt] = malloc ((len+1) * sizeof(char)); strcpy (words[cnt], in_word); cnt++; } sort_words (words, cnt); print_words (words, cnt); }

43 Ragged Arrays – Example void sort_words (char *w[], int n) { int i, j; for (i = 0; i < n; i++) for (j = i + 1; j < n; j++) if (strcmp (w[i], w[j]) > 0) swap_char_ptrs (&w[i], &w[j]); } void print_words (char *w[], int n) { int i; for (i = 0; i < n; i++) printf ("%s ", w[i]); printf ("\n"); }

44 Initialization of Pointer Arrays  Pointer arrays may be initialized not only dynamically, but also statically:  The syntax is similar to the initialization of a two-dimensional array: char *words[] = { "this", "is", "a", "list", "of", "words" }; char words[][10] = { "this", "is", "a", "list", "of", "words" };

45 Initialization of Pointer Arrays – Example  We could have written our word sorting program to work on a static list of words: int main() { char *words[] = { "this", "is", "a", "list", "of", "words" }; int cnt = sizeof (words) / sizeof (char *); sort_words (words, cnt); print_words (words, cnt); } a is list of this words

46 Lecture Overview  Strings and characters  String functions in the standard library  sizeof Revisited  Multidimensional arrays  Pointers to pointers and pointer arrays  Pointers to functions

47 Pointers to Functions  In C, pointers can point to anything, including functions  Pointers to functions can be used just like any other pointers. They can be: Used in assignments Placed in arrays Passed as arguments Returned by functions

48 Pointers to Functions  To define a variable of type pointer to function, we use a definition such as:  This sets up f_ptr as a pointer to a function that accepts no arguments, and returns int  The parenthesis in the definition are mandatory int (*f_ptr)();

49 Pointers to Functions – Example #include #define PI double my_tan (double x); int main() { double x = PI / 4; double (*f)(double x); f = sin; printf ("f(x): %f\n", (*f)(x)); f = cos; printf ("f(x): %f\n", (*f)(x)); f = my_tan; printf ("f(x): %f\n", (*f)(x)); }...

50 Pointers to Functions – Example  The printf lines are similar, but the result is different each time, because the value of f changes... double my_tan (double x) { return sin(x) / cos (x); } f(x): f(x):

51 Pointers to Functions  Without the parenthesis f will be a function returning pointer to double :  On the other hand, in the usage of f the parenthesis can be dropped: is equivalent to:  The parenthesis are used for clarity and for consistency with the definition double *f(double x); (*f)(x)f(x)

52 Pointers to Functions Passed as Arguments – Example  We define a function that accepts a pointer to another function as an argument  The passed function is then activated: #include #define PI double square_f (double (*f)(double y), double x) { double f_val = (*f)(x); return pow (f_val, 2); }...

53 Pointers to Functions Passed as Arguments – Example... double identity (double x) { return x; } int main (int argc, char *argv[]) { double x = PI / 4; printf ("sin(PI/4)^2: \t%f\n", square_f (sin, x)); printf ("cos(0)^2: \t%f\n", square_f (cos, 0)); printf ("2^2: \t%f\n", square_f (identity, 2)); } sin(PI/4)^2: cos(0)^2: ^2:

54 Arrays of Pointers to Functions  Finally, we show how function pointers can be used as array elements  This can significantly increase the flexibility of the program  Can be useful, for example, to define the behavior of different menu items, by assigning a function to each button

55 Arrays of Pointers to Functions – Example int main (int argc, char *argv[]) { double val, res = -1; char func_name[MAX_WORD_LEN]; char *func_names[] = {"sin", "cos", "tan"}; double (*funcs[])(double) = {sin, cos, tan, exit}; int i, n = sizeof (func_names) / sizeof (char *); while (scanf ("%s %f", func_name, &val) == 2) { for (i = 0; i < n; i++) if (!strcmp (func_names[i], func_name)) break; res = (*funcs[i])(val); printf ("%f\n", res); }

56 Simplifying Complicated Declarations  One of the weaknesses of C is that variable declarations may become too complex  In the previous example, it is not easy to understand what is the type of funcs  If we define a function pointer as: then the definition of funcs is simplified: Func_ptr funcs[] = {sin, cos, tan, exit}; typedef double (*Func_ptr)(double);