Presentation is loading. Please wait.

Presentation is loading. Please wait.

CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.

Similar presentations


Presentation on theme: "CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings."— Presentation transcript:

1 CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings

2 Strings in C A char array, terminated by '\0' String literal – anything enclosed in double quotes –e.g., "cat" – automatically includes terminator Must allocate memory to store the characters char sentence[50]; /* up to 49 chars plus '\0' */ char word[] = "cat"; /* length is 3, but size is 4 */ Point to such memory with char* (pointer to char) char *s = sentence; s = word; cat\0

3 Strings in C Equivalent declarations of a string char filename[11] = “sensor.txt”; char filename[] = “sensor.txt”; char filename[] = {‘s’, ‘e’, ‘n’, ‘s’, ‘o’, ‘r’, ‘.’, ‘t’, ‘x’, ‘t’, ‘\0’};

4 Using pointer arithmetic to traverse a string Example: compute the length of a string by traversing it by incrementing a pointer until reaching the end of the string The difference between the final value of the pointer and the beginning of the string array will give you the length char *p = word; while (*p++ != '\0') ; /* empty loop moves p to end */ printf("length: %d", p – word - 1); This is just an example to demonstrate pointer arithmetic, use strlen function in string.h if you want to get the length of a string

5 Copying string t to string s void stringcopy(char *s, char *t) One way to implement – use subscript notation: int i = 0; while ((s[i] = t[i]) != ‘\0’) i++; Another way – use the pointer parameters: while ((*s = *t) != ‘ \0 ’ ) { s++; t++; } Can just increment in the while header: while ((*s++ = *t++) != ‘ \0 ’ ); And it’s possible to be even more cryptic: while (*s++ = *t++); /* works because value of ‘\0’ is 0 */ These are just examples demonstrating pointer arithmetic, use strcpy function in string.h to copy strings.

6 String library functions The standard C library contains a number of functions for strings which are defined in string.h : strlen(t) : Returns the length of the string s. strcopy(s, t) : Copies string t to string s and returns a pointer to s. strcat(s, t) : Concatenates string t to the end of string s. strcmp(s, t): Compares string s to string t in an element-by-element comparison. A negative values is returned if s t ;

7 Why do we have to deal with pointers? Given that programming using pointers seems somewhat challenging, why do we need them? One reason is, as we have seen earlier, pointers allow us to write functions with side-effects, i.e., the changes made in the function body are reflected to the caller –You have to use this carefully since side-effects are hard to understand when someone else looks at your code. A more significant reason for using pointers is that, without pointers, we would be forced to know the size of each memory we plan to allocate before runtime –We would need to know the sizes of the arrays we plan to allocate for example –But sometimes, the size of an array we plan to allocate may depend on the size of the input. What can we do?

8 Two ways to allocate memory Static memory allocation – done at compile-time int x; double a[5]; /* allocates space for 1 int, 5 doubles */ –Both size and type are clearly specified ahead of time – x can only hold int values, a only double s Dynamic memory allocation – done during execution –Must use library methods like malloc malloc allocates specific amount of memory, returns void * –Cast to appropriate pointer type – then use as always int *ip = (int *)malloc(sizeof(int)); Notes: returns NULL if memory not available so must check that; cast is optional –Must free the memory when done with it: free(ip);

9 What is sizeof ? A unary operator – computes the size, in bytes, of any object or type –Usage: sizeof object or sizeof(type) –If x is an int, sizeof x == sizeof(int) is true Works for arrays too – total bytes in whole array Actual type of result is size _ t –An unsigned integer defined in –Similarly, ptrdiff _ t is result type of pointer subtraction Especially useful to find the sizes of data structures

10 The malloc function malloc is used for dynamic memory allocation The argument of the malloc function is the number of bytes of memory required (where each byte is 8 bits). For example, if we want to allocate a memory for 10 integers, we need to figure out how many bytes we need per integer and then multiple that by 10. –We can use sizeof(int) to get the number of bytes used per integer value Note that this value is system dependent If there is not enough memory for allocation, then malloc returns NULL calloc : like malloc but initializes the allocated memory to 0 realloc : can be used to change the size of the allocated memory

11 Pointers to functions Functions are also stored in memory too –A function’s name “points” to its address Awkward declarations of function pointers –e.g., int (*func)(int, int) declares func as a pointer to a function that takes two ints and returns an int –Like all pointers, especially useful as function parameters (in other functions) See …/demos/funcptr.cfuncptr.c

12 Pointer tutorial Pointer fun http://www.cs.ucsb.edu/~mikec/cs16/slides/binky.html

13 Topics we have discussed after the first midterm Generating “random” values File IO Functions –Parameter passing –Scope, global vs. local variables –Recursive functions Arrays –Sorting an array –Multi-dimensional arrays –Arrays as function parameters Software life-cycle, testing, assertions Pointers –Address and dereference operators –Pointers and arrays –C strings –dynamic memory allocation

14 Practice problems Match the following black-box testing assertion driver to the following phrases A Boolean expression that is expected to hold at a particular program point A piece of code that provides the necessary inputs to the module under test A testing method that is synonymous to functional testing

15 Practice Problems Given the following piece of code int *a, *b; a = (int *)malloc(sizeof(int)); b = (int *)malloc(sizeof(int)); *a = 5; *b = 17; printf("Values: %d, %d\n", *a, *b); printf("Values: %u, %u\n", a, b); What will be printed ? What will be printed if we put the assignment a = b; before the print statements? How can you swap the values stored at a and b ? What would happen if we tried this: b = 17; ?

16 Practice problems What does the following function do? void switch(int a, int b) { int hold; hold = a; a = b; b = hold; return; }

17 Practice problems Write a function that computes the sum of elements in an array Write a recursive function that computes the sum of elements in an array

18 Practice problems The practice problems and problems in your text book!


Download ppt "CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings."

Similar presentations


Ads by Google