Programming in C. 3. Pointers and Structures. Dr. Neel Krishnaswami University of Cambridge

Similar documents
Programming in C. 4. Misc. Library Features, Gotchas, Hints and Tips. Dr. Neel Krishnaswami University of Cambridge

Programming in C and C++

Arrays and Pointers in C. Alan L. Cox

C and C++ 1. Types Variables Expressions & Statements. Andrew W. Moore

C and C++ 1. Types Variables Expressions & Statements. Andrew W. Moore

C and C++ 2. Functions Preprocessor. Alan Mycroft

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Array Initialization

Programming in C - Part 2

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

CS240: Programming in C

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

High Performance Computing in C and C++

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Programming in C and C++

Language comparison. C has pointers. Java has references. C++ has pointers and references

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

C++ for Java Programmers

Course organization. Course introduction ( Week 1)

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

Fundamental of Programming (C)

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

Programming in C. What is C?... What is C?

Pointers. Pointer References

CS240: Programming in C

Programming in C and C++

CSC 2400: Computer Systems. Arrays and Strings in C

Programming in C and C++

Character Strings. String-copy Example

CSC 2400: Computer Systems. Arrays and Strings in C

Fundamentals of Programming. Lecture 12: C Structures, Unions, Bit Manipulations and Enumerations

Computer Organization & Systems Exam I Example Questions

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Arrays and Pointers. CSE 2031 Fall November 11, 2013

COMP26120: Linked List in C (2018/19) Lucas Cordeiro

I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub

What have we learned about when we learned about function parameters? 1-1

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

Arrays and Pointers in C & C++

Pointers, Dynamic Data, and Reference Types

CS 0449 Sample Midterm

Structures, Unions, and Typedefs

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

ELEC 377 C Programming Tutorial. ELEC Operating Systems

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Programming in C. Lecture 9: Tooling. Dr Neel Krishnaswami. Michaelmas Term

Control flow and string example. C and C++ Functions. Function type-system nasties. 2. Functions Preprocessor. Alastair R. Beresford.

Chapter Overview. Pointers and Dynamic Arrays. Pointers. Pointers. Declaring Pointers. Pointers Tell Where To Find A Variable. 9.

Contents. Custom data type struct data type Fixed length memory Alias data type

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Midterm Exam 2 Solutions C Programming Dr. Beeson, Spring 2009

Structures, Unions Alignment, Padding, Bit Fields Access, Initialization Compound Literals Opaque Structures Summary. Structures

Lectures 5-6: Introduction to C

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

MYcsvtu Notes LECTURE 34. POINTERS

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

Procedural programming with C

Mechatronics and Microcontrollers. Szilárd Aradi PhD Refresh of C

C and C++ 7. Exceptions Templates. Alan Mycroft

INTRODUCTION 1 AND REVIEW

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

DECLARAING AND INITIALIZING POINTERS

Lecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

Lectures 5-6: Introduction to C

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

EM108 Software Development for Engineers

CS 261 Fall Mike Lam, Professor. Structs and I/O

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Pointers. Pointers. Pointers (cont) CS 217

Introduction to Scientific Computing and Problem Solving

C++ Programming Chapter 7 Pointers

Pointers, References and Arrays

Quiz 0 Answer Key. Answers other than the below may be possible. Multiple Choice. 0. a 1. a 2. b 3. c 4. b 5. d. True or False.

Binghamton University. CS-211 Fall Pointers

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

(heavily based on last year s notes (Andrew Moore) with thanks to Alastair R. Beresford. 1. Types Variables Expressions & Statements 2/23

by Pearson Education, Inc. All Rights Reserved.

Contents. A Review of C language. Visual C Visual C++ 6.0

CSE 333 Lecture 2 Memory

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

Informatica 3 Syntax and Semantics

Pointers. 10/5/07 Pointers 1

Programming for Electrical and Computer Engineers. Pointers and Arrays

Variables, Pointers, and Arrays

arrays review arrays and memory arrays: character array example cis15 advanced programming techniques, using c++ summer 2008 lecture # V.

CSE 220: Systems Programming

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Procedural Programming & Fundamentals of Programming

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Transcription:

Programming in C 3. Pointers and Structures Dr. Neel Krishnaswami University of Cambridge (based on notes from and with thanks to Anil Madhavapeddy, Alan Mycroft, Alastair Beresford and Andrew Moore) Michaelmas Term 2017-2018

Pointers Computer memory is often abstracted as a sequence of bytes, grouped into words Each byte has a unique address or index into this sequence The size of a word (and byte!) determines the size of addressable memory in the machine A pointer in C is a variable which contains the memory address of another variable (this can, itself, be a pointer) Pointers are declared or defined using an asterisk(*); for example: char *pc; or int **ppi; The asterisk binds to the variable name, not the type specifier; for example char *pc,c; A pointer does not necessarily take the same amount of storage space as the type it points to 2 / 25

Example 52 00... 00 00... 1c 00 41 Little... 00 00 42 00 41 Big 05 62 0x2c 0x30 0x34 0x38 0x4c 0x50 0x60 int **ppi int *pi int i char *pc char c 00 00 38 4c 3 / 25

Manipulating pointers The value pointed to by a pointer can be retrieved or dereferenced by using the unary * operator; for example: int *p =... int x = *p; The memory address of a variable is returned with the unary ampersand (&) operator; for example int *p = &x; Dereferenced pointer values can be used in normal expressions; for example: *pi += 5; or (*pi)++ 4 / 25

Example 1 #include <stdio.h> 2 3 int main(void) { 4 int x=1,y=2; 5 int *pi; 6 int **ppi; 7 8 pi = &x; ppi = π 9 printf("%p, %p, %d=%d=%d\n",ppi,pi,x,*pi,**ppi); 10 pi = &y; 11 printf("%p, %p, %d=%d=%d\n",ppi,pi,y,*pi,**ppi); 12 13 return 0; 14 } 5 / 25

Pointers and arrays A C array uses consecutive memory addresses without padding to store data An array name (used in an expression without an index) represents the memory address of the first element of the array; for example: char c[10]; char *pc = c; is the same as char *pc = &c[0]; Pointers can be used to index into any element of an array; for example: int i[10]; int *pi = &i[5]; 6 / 25

Pointer arithmetic Pointer arithmetic can be used to adjust where a pointer points; for example, if pc points to the first element of an array, after executing pc+=3; then pc points to the fourth element A pointer can even be dereferenced using array notation; for example pc[2] represents the value of the array element which is two elements beyond the array element currently pointed to by pc In summary, for an array c, *(c+i) c[i] and c+i &c[i] A pointer is a variable, but an array name is not; therefore pc=c and pc++ are valid, but c=pc and c++ are not 7 / 25

Example 1 #include <stdio.h> 2 3 int main(void) { 4 char str[] = "A string."; 5 char *pc = str; 6 7 printf("%c %c %c\n",str[0],*pc,pc[3]); 8 pc += 2; 9 printf("%c %c %c\n",*pc, pc[2], pc[5]); 10 11 return 0; 12 } 8 / 25

Pointers as function arguments Recall that all arguments to a function are copied, i.e. passed-by-value; modification of the local value does not affect the original In the second lecture we defined functions which took an array as an argument; for example void reverse(char s[]) Why, then, does reverse affect the values of the array after the function returns (i.e. the array values haven t been copied)? because s is re-written to char *s and the caller implicitly passes a pointer to the start of the array Pointers of any type can be passed as parameters and return types of functions Pointers allow a function to alter parameters passed to it 9 / 25

Example Compare swp1(a,b) with swp2(&a,&b): 1 void swp1(int x,int y) 2 { 3 int temp = x; 4 x = y; 5 y = temp; 6 } 1 void swp2(int *px,int *py) 2 { 3 int temp = *px; 4 *px = *py; 5 *py = temp; 6 } 10 / 25

Arrays of pointers C allows the creation of arrays of pointers; for example int *a[5]; Arrays of pointers are particularly useful with strings An example is C support of command line arguments: int main(int argc, char *argv[]) {... } In this case argv is an array of character pointers, and argc tells the programmer the length of the array 11 / 25

Example argv: argc: 3 argv[0] argv[1] argv[2] progname\0 firstarg\0 secondarg\0 argv[3] NULL 12 / 25

Multi-dimensional arrays Multi-dimensional arrays can be declared in C; for example: int i[5][10]; Values of the array can be accessed using square brackets; for example: i[3][2] When passing a two dimensional array to a function, the first dimension is not needed; for example, the following are equivalent: void f(int i[5][10]) {... } void f(int i[][10]) {... } void f(int (*i)[10]) {... } In arrays with higher dimensionality, all but the first dimension must be specified 13 / 25

Pointers to functions C allows the programmer to use pointers to functions This allows functions to be passed as arguments to functions For example, we may wish to parameterise a sort algorithm on different comparison operators (e.g. lexicographically or numerically) If the sort routine accepts a pointer to a function, the sort routine can call this function when deciding how to order values 14 / 25

Example 1 void sort(int a[], const int len, 2 int (*compare)(int, int)) 3 { 4 int i,j,tmp; 5 for(i=0;i<len-1;i++) 6 for(j=0;j<len-1-i;j++) 7 if ((*compare)(a[j],a[j+1])) 8 tmp=a[j], a[j]=a[j+1], a[j+1]=tmp; 9 } 10 11 int inc(int a, int b) { 12 return a > b? 1 : 0; 13 } Source of some confusion: either or both of the *s in *compare may be omitted due to language (over-)generosity. 15 / 25

Example 1 #include <stdio.h> 2 #include "example8.h" 3 4 int main(void) { 5 int a[] = {1,4,3,2,5}; 6 unsigned int len = 5; 7 sort(a,len,inc); //or sort(a,len,&inc); 8 9 int *pa = a; //C99 10 printf("["); 11 while (len--) 12 printf("%d%s",*pa++,len?" ":""); 13 printf("]\n"); 14 15 return 0; 16 } 16 / 25

The void * pointer C has a typeless or generic pointer: void *p This can be a pointer to any object (but not legally to a function) This can be useful when dealing with dynamic memory Enables polymorphic code; for example: 1 sort(void *p, const unsigned int len, 2 int (*comp)(void *,void *)); However this is also a big hole in the type system Therefore void * pointers should only be used where necessary 17 / 25

Structure declaration A structure is a collection of one or more members (fields) It provides a simple method of abstraction and grouping A structure may itself contain structures A structure can be assigned to, as well as passed to, and returned from functions We declare a structure using the keyword struct For example, to declare a structure circle we write struct circle {int x; int y; unsigned int r;}; Declaring a structure creates a new type 18 / 25

Structure definition To define an instance of the structure circle we write struct circle c; A structure can also be initialised with values: struct circle c = {12, 23, 5}; An automatic, or local, structure variable can be initialised by function call: struct circle c = circle_init(); A structure can declared, and several instances defined in one go: struct circle {int x; int y; unsigned int r;} a, b; 19 / 25

Member access A structure member can be accessed using. notation: structname.member; for example: vect.x Comparison (e.g. vect1 > vect2) is undefined Pointers to structures may be defined; for example: struct circle *pc When using a pointer to a struct, member access can be achieved with the. operator, but can look clumsy; for example: (*pc).x Equivalently, the -> operator can be used; for example: pc->x 20 / 25

Self-referential structures A structure declaration cannot contain itself as a member, but it can contain a member which is a pointer whose type is the structure declaration itself This means we can build recursive data structures; for example: 1 struct tree { 2 int val; 3 struct tree *left; 4 struct tree *right; 5 } 1 struct link { 2 int val; 3 struct link *next; 4 } 21 / 25

Unions A union variable is a single variable which can hold one of a number of different types A union variable is declared using a notation similar to structures; for example: union u { int i; float f; char c;}; The size of a union variable is the size of its largest member The type held can change during program execution The type retrieved must be the type most recently stored Member access to unions is the same as for structures (. and -> ) Unions can be nested inside structures, and vice versa 22 / 25

Bit fields Bit fields allow low-level access to individual bits of a word Useful when memory is limited, or to interact with hardware A bit field is specified inside a struct by appending a declaration with a colon (:) and number of bits; for example: struct fields { int f1 : 2; int f2 : 3;}; Members are accessed in the same way as for structs and unions A bit field member does not have an address (no & operator) Lots of details about bit fields are implementation specific: word boundary overlap & alignment, assignment direction, etc. 23 / 25

Example (adapted from K&R) 1 struct { /* a compiler symbol table */ 2 char *name; 3 struct { 4 unsigned int is_keyword : 1; 5 unsigned int is_extern : 1; 6 unsigned int is_static : 1; 7... 8 } flags; 9 int utype; 10 union { 11 int ival; /* accessed as symtab[i].u.ival */ 12 float fval; 13 char *sval; 14 } u; 15 } symtab[nsym]; 24 / 25

Exercises 1. If p is a pointer, what does p[-2] mean? When is this legal? 2. Write a string search function with a declaration of char *strfind(const char *s, const char *f); which returns a pointer to first occurrence of the string s in the string f (and NULL otherwise) 3. If p is a pointer to a structure, write some C code which uses all the following code snippets: ++p->i, p++->i, *p->i, *p->i++, (*p->i)++ and *p++->i ; describe the action of each code snippet 4. Write a program calc which evaluates a reverse Polish expression given on the command line; for example $ calc 2 3 4 + * should print 14 (K&R Exercise 5-10) 25 / 25