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

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

Programming and Data Structure
Programming Languages and Paradigms The C Programming Language.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
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.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Pointers in C Rohit Khokher
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
1 Objectives ❏ To understand the relationship between arrays and pointers ❏ To understand the design and concepts behind pointer arithmetic ❏ To write.
Kernighan/Ritchie: Kelley/Pohl:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Chapter 10.
Introduction to C Programming CE Lecture 18 Dynamic Memory Allocation and Ragged Arrays.
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.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
Pointers Applications
C Arrays and Pointers In Java, pointers are easy to deal with –In fact, there is little that can go wrong in Java since pointer access is done for you.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
Stack and Heap Memory Stack resident variables include:
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
CS 261 – Data Structures Introduction to C Programming.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 13: Data structures in C.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
CSC Programming for Science Lecture 34: Dynamic Pointers.
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
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.
19-Feb-02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Arrays, Pointers, Strings Lecture 18 19/2/2002.
Pointer Variables A pointer is a variable that contains a memory address The address is commonly the location of another variable in memory This pointer.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Dynamic Allocation in C
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Programming Languages and Paradigms
Lecture 6 C++ Programming
Pointers and Pointer-Based Strings
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
CS111 Computer Programming
Programming Languages and Paradigms
Presentation transcript:

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

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

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’};

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

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.

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 ;

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?

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);

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

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

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

Pointer tutorial Pointer fun

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

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

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; ?

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

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

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