Introduction to C: Pointers

Similar documents
Reference operator (&)

Pointers. Reference operator (&) ted = &andy;

12. Pointers Address-of operator (&)

Pointers in C/C++ 1 Memory Addresses 2

Memory and Addresses. Pointers in C. Memory is just a sequence of byte-sized storage devices.

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C++ for Java Programmers

Lecture 04 Introduction to pointers

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

CS61C : Machine Structures

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

Goals of this Lecture

CSCI 171 Chapter Outlines

CS 222: Pointers and Manual Memory Management

CS61C Machine Structures. Lecture 5 C Structs & Memory Mangement. 1/27/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

CS 61c: Great Ideas in Computer Architecture

Homework #3 CS2255 Fall 2012

Pointers. Memory. void foo() { }//return

C++ Programming Chapter 7 Pointers

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Memory Corruption 101 From Primitives to Exploit

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

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


Ch. 11: References & the Copy-Constructor. - continued -

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

CS 31: Intro to Systems Arrays, Structs, Strings, and Pointers. Kevin Webb Swarthmore College March 1, 2016

[0569] p 0318 garbage

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Final CSE 131B Spring 2004

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

Lecture 5: Outline. I. Multi- dimensional arrays II. Multi- level arrays III. Structures IV. Data alignment V. Linked Lists

Programming in C - Part 2

by Pearson Education, Inc. All Rights Reserved.

2/28/2018. Overview. The C Programming Language Part 4. Pointers. Pointers. Pointers. Pointers

The C Programming Language Part 4. (with material from Dr. Bin Ren, William & Mary Computer Science, and

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

Intermediate Programming, Spring 2017*

QUIZ. What are 3 differences between C and C++ const variables?

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

C Praktikum. Advanced Pointers. Eugen Betke, Nathanael Hübbe, Michael Kuhn, Jakob Lüttgau, Jannek Squar

SYSC 2006 C Winter 2012

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

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

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

QUIZ. What is wrong with this code that uses default arguments?

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

Object oriented programming C++

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong

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

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

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

today cs3157-fall2002-sklar-lect05 1

CS201 Latest Solved MCQs

Dynamic memory allocation

Please refer to the turn-in procedure document on the website for instructions on the turn-in procedure.

A brief introduction to C programming for Java programmers

CS61C : Machine Structures

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

CS 61C: Great Ideas in Computer Architecture Introduction to C

Singly linked lists in C.

Slide Set 6. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

Data Structure Series

CS201 Some Important Definitions

Professor Terje Haukaas University of British Columbia, Vancouver C++ Programming

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

void setup(){ void loop() { The above setup works, however the function is limited in the fact it can not be reused easily. To make the code more gene

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Character Strings. String-copy Example

CS61C : Machine Structures

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Chapter 1: Object-Oriented Programming Using C++

Procedures, Parameters, Values and Variables. Steven R. Bagley

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

FUNCTIONS POINTERS. Pointers. Functions

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

CS 2461: Computer Architecture I

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

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

Final CSE 131B Spring 2005

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

Introduction to C++ with content from

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

EL2310 Scientific Programming

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Arrays and Pointers in C & C++

Transcription:

Introduction to C: Pointers <Pointer> <Objects> <Pointer> Nils Moschüring PhD Student (LMU) Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 1

1 Introduction 2 Pointers Basics Useful: Function arguments Useful: Arrays Double Pointers void Pointers 3 Function pointers 4 Riddle & End Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 2

Introduction Pointers are a specific type of variable available in some programming languages, most notably C and C++. The history of pointers is comprised of opposites: they enable greatness they promote readability they are the best thing about C they enable great fubarness they exist only to brag they are the most evil thing about C Of course, both sides are totally right. That s why they are interesting to understand. Many modern programming languages have abolished them. The PSC makes heavy use of them. Important term: ud=undefined behaviour Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 4

Memory and Values This is our physical memory. Each memory is referred to by a unique address. Value Address #1 #2 #3 #4 #5 #6 #7 #8 After 1 i n t i = 3; we get: Value 3 Address #1 #2 #3 #4 #5 #6 #7 #8 The address of object i is #2. The OS decides that! Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 5

So what do pointers do? Let s define and initialize a pointer: 1 i n t i p = NULL; Result: Value 3 Null Address #1 #2 #3 #4 #5 #6 #7 #8 Now we let it point to i by setting the value of ip to &i: 2 i p = & i ; The ampersand (&) is called address of or reference operator. Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 7

So what do pointers do? Now we get this: Value 3 #2 Address #1 #2 #3 #4 #5 #6 #7 #8 And the following is true: 1 i == 3; 2 i p == 3; 3 i p == #2 == & i ; 4 &i p == #5; The asterisk ( ) is called value of or dereference operator. Note: The asterisk in the definition of ip is not an operator, but a part of the variable type (ip is of type pointer to int). Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 8

What s the use? Why do we need them? Call by Reference Call by Value Less copying Return more values New array manipulation techniques. C Arrays are always pointers! Messing things up really hard. What do other languages do? They all utilize pointers, but you can not directly control them. Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 9

Function arguments and pointers Our code: 1 struct b i g S t r u c t { 2 i n t s t u f f [ 2 0 0 ] ; 3 } ; 4 i n t main ( ) { 5 struct b i g S t r u c t mybigstruct ; 6 func ( mybigstruct ) ; 7 return 1; 8 } Now we want to do stuff in this function. One way: 9 i n t func ( struct b i g S t r u c t a ) { 10 p r i n t f ( %d\n, a. s t u f f [ 5 0 ] ) ; 11 } THIS IS BAD! Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 10

Function arguments and pointers Better way to do it: 1 i n t func ( struct b i g S t r u c t * a ) { 2 p r i n t f ( %d\n, a >s t u f f [ 5 0 ] ) ; 3 } 4 i n t main ( ) { 5 struct b i g S t r u c t mybigstruct ; 6 func (& mybigstruct ) ; 7 return 0; 8 } This won t copy anything but ONE address (4-8 byte)! And you can write, not only read, all the values! Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 11

Pointers to struct What s the arrow? 1 p r i n t f ( %d\n, a >s t u f f [ 5 0 ] ) ; It must be equal to: 2 p r i n t f ( %d\n, ( a ). s t u f f [ 5 0 ] ) ; So it s a shortcut which makes the code much easier to read. The arrow operator, -> (that s a minus sign followed immediately by a greater than), dereferences a pointer to select a field. Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 12

Arrays in C and C++ What happens when creating an array? 1 i n t array [ 5 ] ; It looks strange, but this: Value #3 Address #1 #2 #3 #4 #5 #6 #7 #8 With the following true: 2 array == #3; 3 &array == #3; The first expression shows the automatic decay mechanism of C: The array automatically decays into the pointer pointing to it when only referenced by its name (in most cases). How is that an array?! Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 13

Arrays in C and C++ Let s find out! You could do, for example: 1 array [ 0 ] = 9; now, in the physical memory, you would like to have: Value #3 9 Address #1 #2 #3 #4 #5 #6 #7 #8 And this is what you get! So what is this [0] operator doing? It must be equal to the asterisk! Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 14

Arrays in C and C++ But what about: 1 array [ 3 ] = 10; You will get: Value #3 9 10 Address #1 #2 #3 #4 #5 #6 #7 #8 So the above equals to: 2 ( array + 3) = 10; The jumping increment is determined by the pointer type (no void pointers UD!). The [] is called offset operator. Note: The brackets in the definition of array are not operators, they are part of the type array. Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 15

Summary of Arrays in C and C++ 1 i n t array [ 5 ] ; 2 i n t const array = ( i n t ) malloc ( sizeof ( array ) 5 ) ; What does this do: 3 char p = NULL; 4 for ( p = N i l s ; p!= \0 ; p++) { 5 p r i n t f ( %c, p ) ; 6 } CORRECT! Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 16

Constant strings in depth What is Nils equal to? C will create a constant string in a buffer by internally calling something like: 1 const char b u f f e r [ 5 ] ; But what does this mean? Inserting the approximation given above, it should approximately be: 2 const char const b u f f e r =( char ) malloc ( sizeof ( b u f f e r ) 5 ) ; After that, C will insert the characters and add a trailing \0. Nils is a pointer type object with two specialties: Its value (i.e. the address it points to) can not be written (the second const). 3 / N i l s = / b u f f e r =& i ; / / Compiler e r r o r The memory to which it points can not be written (the first const). 4 / N i l s [ 1 ] = / b u f f e r [ 1 ] = o ; / / Compiler / runtime e r r o r Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 17

Higher Dimensional Arrays Think about this statement: 1 i n t array2d [ 1 0 ] [ 1 0 ] ; According to what we ve seen so far, the following 2 array2d [ 2 ] [ 3 ] = 4; means: 3 ( ( array2d + 2) + 3) = 4; An array of pointers, pointed to by our array variable. Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 18

Obvious follow-up: Pointers to Pointers We declare and assign a double pointer: 1 i n t ipp = &i p ; Now we ll get this: Value 3 #2 #5 Address #1 #2 #3 #4 #5 #6 #7 #8 If the address of ipp is #7. Things that are true in this case: 2 i == i p == ipp == 3; 3 ipp == i p == & i == #2; 4 ipp == &i p == #5; 5 &ipp == #7; Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 19

What s the use of this mess? (except multidimensional arrays) You can thus change where the pointers are pointing to! 1 i n t j ; 2 ipp = & j ; Now, if the address of j is #4, you ll get this: Value 3 #4 #5 Address Variable #1 #2 #3 #4 #5 #6 #7 #8 i j ip ipp This enables you to change the targets of pointers via functions. In certain situations this can make the code far better. (and really difficult to understand) Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 20

Traps and problems Suppose you need a function which creates a list of objects for you: 1 struct m y s t r u c t l i s t ; 2 generate my structs (& l i s t ) ; Double pointers are needed! Lets look at this function: 3 void generate my structs ( struct m y s t r u c t l i s t ) { 4 l i s t = malloc (5 sizeof ( l i s t ) ) ; How can write a data field of the second object? 5 ( l i s t ) [ 2 ]. a t t r = 5; 6 } wrong (operator precedence): 7 l i s t [2] > a t t r = 5; 8 * l i s t [ 2 ]. a t t r = 5; First one will not produce a compilation error! In most cases not even a runtime error! Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 21

Solution to this Avoid double pointers. Seriously. How to do it without them? Use more levels of structures No double pointers needed Extra level of names which always helps to clarify the code 1 struct m y l i s t s t r u c t { 2 struct m y s t r u c t l i s t ; 3 } ; 4 void generate ( struct m y l i s t s t r u c t l i s t s t r u c t ) { 5 l i s t s t r u c t > l i s t = 6 malloc (5 sizeof ( l i s t s t r u c t > l i s t ) ) ; 7 l i s t s t r u c t > l i s t [ 2 ]. a t t r = 5; 8 } 9 struct m y l i s t s t r u c t l i s t s t r u c t ; 10 generate (& l i s t s t r u c t ) ; Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 22

void Pointers It s a special type of Pointer Pointers pointing to a value that has no type They can point to any datataype (and even functions) They are essentially just bare pointers, just addresses They can t be directly dereferenced, as the result wouldn t have a type You need to always typecast them to a different pointer type before dereferencing. Example: 1 i n t main ( ) { 2 void vp = malloc ( sizeof ( i n t ) ) ; 3 p r i n t f ( %d\n, ( ( i n t ) vp ) ) ; 4 f r e e ( vp ) ; 5 return 0; 6 } Incrementing and decrementing (or using the offset operator) will use 1 byte as the step size (even though sizeof(void) does not work). Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 23

void Pointers, two examples The malloc function Definition: 1 void malloc ( s i z e t size ) ; The OS never knows about the type of your memory But it does remember its length. void function arguments 2 void increase ( void data, i n t psize ) { 3 i f ( psize == sizeof ( char ) ) 4 { char pchar ; pchar = ( char ) data ; ++( pchar ) ; } 5 else i f ( psize == sizeof ( i n t ) ) 6 { i n t p i n t ; p i n t = ( i n t ) data ; ++( p i n t ) ; } 7 } Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 24

Function pointers You can create pointers to functions. This enables, among other things, Late-Binding (PSC!). Declaration: 1 i n t ( fp ) ( int, i n t ) ; This is a function pointer to a function of the following type: return value: int two int arguments Functions with prototype: int function( int, int ); Assignement & Function call: 2 fp = &f u n c t i o n ; 3 ( fp ) ( 1, 1 ) ; / / Employing the ( ) f u n c t i o n c a l l operator The Ampersand can also be left out, since function pointers are also subject to automatic decay. Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 26

Function pointers, example Obligatory senseless example: 1 i n t s u b s t r a c t i o n ( i n t i, i n t j ){ return i j ; } 2 i n t plus ( i n t i, i n t j ){ return i + j ; } 3 i n t operation ( i n t i, i n t j, i n t ( fp ) ( int, i n t ) ) { 4 return ( fp ) ( i, j ) ; 5 } 6 i n t main ( ) { 7 i n t ( minus ) ( int, i n t ) = &s u b s t r a c t i o n ; 8 p r i n t f ( %d\n, operation ( 1, 1, minus ) ) ; 9 p r i n t f ( %d\n, operation ( 1, 1, &plus ) ) ; 10 return 0; 11 } 11 0 12 2 Returns: Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 27

Riddle & End 1 i n t number ( i n t i ){ return i 3;} 2 i n t main ( i n t arg ) { 3 s t a t i c i n t count = 0; 4 i n t ( f p a r r a y [ 1 0 ] ) ( i n t ) ; 5 for ( i n t i =0; i <10; i ++) f p a r r a y [ i ] = &number ; 6 ( f p a r r a y + 4) = &main ; 7 for ( i n t i = ( f p a r r a y[ arg ] ) ( arg ) ; i <10; i ++) { 8 p r i n t f ( %d, ( ( f p a r r a y + i ) ) ( i ) ) ; 9 count ++; i f ( count >5) break ; 10 } 11 return 666; 12 } 13 036927666 Take-Home-Message Now you re thinking in pointers... Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 29