Introduction to C: Pointers

Size: px
Start display at page:

Download "Introduction to C: Pointers"

Transcription

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

2 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

3 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

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

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

6 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

7 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

8 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 [ ] ; 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

9 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

10 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

11 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

12 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

13 Arrays in C and C++ But what about: 1 array [ 3 ] = 10; You will get: Value # 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

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 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

22 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

23 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

24 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 } Returns: Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 27

25 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 } Take-Home-Message Now you re thinking in pointers... Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 29

Reference operator (&)

Reference operator (&) Pointers Each cell can be easily located in the memory because it has a unique address and all the memory cells follow a successive pattern. For example, if we are looking for cell 1776 we know that it

More information

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

Pointers. Reference operator (&)  ted = &andy; Pointers We have already seen how variables are seen as memory cells that can be accessed using their identifiers. This way we did not have to care about the physical location of our data within memory,

More information

12. Pointers Address-of operator (&)

12. Pointers Address-of operator (&) 12. Pointers In earlier chapters, variables have been explained as locations in the computer's memory which can be accessed by their identifer (their name). This way, the program does not need to care

More information

Pointers in C/C++ 1 Memory Addresses 2

Pointers in C/C++ 1 Memory Addresses 2 Pointers in C/C++ Contents 1 Memory Addresses 2 2 Pointers and Indirection 3 2.1 The & and * Operators.............................................. 4 2.2 A Comment on Types - Muy Importante!...................................

More information

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

Memory and Addresses. Pointers in C. Memory is just a sequence of byte-sized storage devices. Memory and Addresses Memory is just a sequence of byte-sized storage devices. 1 The bytes are assigned numeric addresses, starting with zero, just like the indexing of the cells of an array. It is the

More information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

Lecture 04 Introduction to pointers

Lecture 04 Introduction to pointers Lecture 04 Introduction to pointers A pointer is an address in the memory. One of the unique advantages of using C is that it provides direct access to a memory location through its address. A variable

More information

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

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory Pointers A pointer is simply a reference to a variable/object Compilers automatically generate code to store/retrieve variables from memory It is automatically generating internal pointers We don t have

More information

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

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57 Comp 11 Lectures Mike Shah Tufts University June 26, 2017 Mike Shah (Tufts University) Comp 11 Lectures June 26, 2017 1 / 57 Please do not distribute or host these slides without prior permission. Mike

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 4 Introduction to C (pt 2) 2014-09-08!!!Senior Lecturer SOE Dan Garcia!!!www.cs.berkeley.edu/~ddgarcia! C most popular! TIOBE programming

More information

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

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays C Arrays This handout was written by Nick Parlante and Julie Zelenski. As you recall, a C array is formed by laying out all the elements

More information

Goals of this Lecture

Goals of this Lecture C Pointers Goals of this Lecture Help you learn about: Pointers and application Pointer variables Operators & relation to arrays 2 Pointer Variables The first step in understanding pointers is visualizing

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

CS 222: Pointers and Manual Memory Management

CS 222: Pointers and Manual Memory Management CS 222: Pointers and Manual Memory Management Chris Kauffman Week 4-1 Logistics Reading Ch 8 (pointers) Review 6-7 as well Exam 1 Back Today Get it in class or during office hours later HW 3 due tonight

More information

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

CS61C Machine Structures. Lecture 5 C Structs & Memory Mangement. 1/27/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/ CS61C Machine Structures Lecture 5 C Structs & Memory Mangement 1/27/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L05 C Structs (1) C String Standard Functions

More information

CS 61c: Great Ideas in Computer Architecture

CS 61c: Great Ideas in Computer Architecture Arrays, Strings, and Some More Pointers June 24, 2014 Review of Last Lecture C Basics Variables, functioss, control flow, types, structs Only 0 and NULL evaluate to false Pointers hold addresses Address

More information

Homework #3 CS2255 Fall 2012

Homework #3 CS2255 Fall 2012 Homework #3 CS2255 Fall 2012 MULTIPLE CHOICE 1. The, also known as the address operator, returns the memory address of a variable. a. asterisk ( * ) b. ampersand ( & ) c. percent sign (%) d. exclamation

More information

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

Pointers. Memory. void foo() { }//return Pointers Pointers Every location in memory has a unique number assigned to it called it s address A pointer is a variable that holds a memory address A pointer can be used to store an object or variable

More information

C++ Programming Chapter 7 Pointers

C++ Programming Chapter 7 Pointers C++ Programming Chapter 7 Pointers Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics & Department

More information

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

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables Chapter 11 Pointers The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into bytes, with each byte capable

More information

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

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016 CS 31: Intro to Systems Pointers and Memory Martin Gagne Swarthmore College February 16, 2016 So we declared a pointer How do we make it point to something? 1. Assign it the address of an existing variable

More information

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

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/ CS61C Machine Structures Lecture 4 C Structs & Memory Management 9/5/2007 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Structs (1) C String Standard Functions

More information

Memory Corruption 101 From Primitives to Exploit

Memory Corruption 101 From Primitives to Exploit Memory Corruption 101 From Primitives to Exploit Created by Nick Walker @ MWR Infosecurity / @tel0seh What is it? A result of Undefined Behaviour Undefined Behaviour A result of executing computer code

More information

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

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as

More information

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

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018 CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make

More information

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

COMP26120: Pointers in C (2018/19) Lucas Cordeiro COMP26120: Pointers in C (2018/19) Lucas Cordeiro lucas.cordeiro@manchester.ac.uk Organisation Lucas Cordeiro (Senior Lecturer, FM Group) lucas.cordeiro@manchester.ac.uk Office: 2.44 Office hours: 10-11

More information

About Codefrux While the current trends around the world are based on the internet, mobile and its applications, we try to make the most out of it. As for us, we are a well established IT professionals

More information

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

Ch. 11: References & the Copy-Constructor. - continued - Ch. 11: References & the Copy-Constructor - continued - const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed

More information

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

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor CS 261 Fall 2017 Mike Lam, Professor C Introduction Variables, Memory Model, Pointers, and Debugging The C Language Systems language originally developed for Unix Imperative, compiled language with static

More information

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

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6 CMSC 313 Introduction to Computer Systems Lecture 8 Pointers, cont. Alan Sussman als@cs.umd.edu Administrivia Project 2 posted, due October 6 public tests s posted Quiz on Wed. in discussion up to pointers

More information

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

CS 31: Intro to Systems Arrays, Structs, Strings, and Pointers. Kevin Webb Swarthmore College March 1, 2016 CS 31: Intro to Systems Arrays, Structs, Strings, and Pointers Kevin Webb Swarthmore College March 1, 2016 Overview Accessing things via an offset Arrays, Structs, Unions How complex structures are stored

More information

[0569] p 0318 garbage

[0569] p 0318 garbage A Pointer is a variable which contains the address of another variable. Declaration syntax: Pointer_type *pointer_name; This declaration will create a pointer of the pointer_name which will point to the

More information

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

C Introduction. Comparison w/ Java, Memory Model, and Pointers CS 261 Fall 2018 Mike Lam, Professor C Introduction Comparison w/ Java, Memory Model, and Pointers Please go to socrative.com on your phone or laptop, choose student login and join room LAMJMU The C Language

More information

Final CSE 131B Spring 2004

Final CSE 131B Spring 2004 Login name Signature Name Student ID Final CSE 131B Spring 2004 Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 Page 7 Page 8 (25 points) (24 points) (32 points) (24 points) (28 points) (26 points) (22 points)

More information

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

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables. When a program is run, memory space is immediately reserved for the variables defined in the program. This memory space is kept by the variables until the program terminates. These variables are called

More information

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.

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. Chapter 9: Pointers 9.1 Getting the Address of a Variable C++ Variables [ not in book ] A Variable has all of the following attributes: 1. name 2. type 3. size 4. value 5. storage class static or automatic

More information

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

Lecture 5: Outline. I. Multi- dimensional arrays II. Multi- level arrays III. Structures IV. Data alignment V. Linked Lists Lecture 5: Outline I. Multi- dimensional arrays II. Multi- level arrays III. Structures IV. Data alignment V. Linked Lists Multidimensional arrays: 2D Declaration int a[3][4]; /*Conceptually 2D matrix

More information

Programming in C - Part 2

Programming in C - Part 2 Programming in C - Part 2 CPSC 457 Mohammad Reza Zakerinasab May 11, 2016 These slides are forked from slides created by Mike Clark Where to find these slides and related source code? http://goo.gl/k1qixb

More information

by Pearson Education, Inc. All Rights Reserved.

by Pearson Education, Inc. All Rights Reserved. Let s improve the bubble sort program of Fig. 6.15 to use two functions bubblesort and swap. Function bubblesort sorts the array. It calls function swap (line 51) to exchange the array elements array[j]

More information

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

2/28/2018. Overview. The C Programming Language Part 4. Pointers. Pointers. Pointers. Pointers Overview The C Programming Language Part 4 (with material from Dr. Bin Ren, William & Mary Computer Science, and www.cpp.com) Basic Concepts of and Arrays and Strings Dynamic Memory Allocation 1 2 pointer

More information

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

The C Programming Language Part 4. (with material from Dr. Bin Ren, William & Mary Computer Science, and The C Programming Language Part 4 (with material from Dr. Bin Ren, William & Mary Computer Science, and www.cpp.com) 1 Overview Basic Concepts of Pointers Pointers and Arrays Pointers and Strings Dynamic

More information

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

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26 COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

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

QUIZ. What are 3 differences between C and C++ const variables? QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,

More information

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

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz CS 61C: Great Ideas in Computer Architecture Lecture 3: Pointers Bernhard Boser & Randy Katz http://inst.eecs.berkeley.edu/~cs61c Agenda Pointers in C Arrays in C This is not on the test Pointer arithmetic

More information

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

C Praktikum. Advanced Pointers. Eugen Betke, Nathanael Hübbe, Michael Kuhn, Jakob Lüttgau, Jannek Squar C Praktikum Advanced Pointers Eugen Betke, Nathanael Hübbe, Michael Kuhn, Jakob Lüttgau, Jannek Squar 2018-11-26 Warning This is a dive under the hood. We will see, and hopefully understand many details

More information

SYSC 2006 C Winter 2012

SYSC 2006 C Winter 2012 SYSC 2006 C Winter 2012 Pointers and Arrays Copyright D. Bailey, Systems and Computer Engineering, Carleton University updated Sept. 21, 2011, Oct.18, 2011,Oct. 28, 2011, Feb. 25, 2011 Memory Organization

More information

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

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology Introduction to C++ Massachusetts Institute of Technology ocw.mit.edu 6.096 Pointers 1 Background 1.1 Variables and Memory When you declare a variable, the computer associates the variable name with a

More information

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

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 Krste Asanović & Randy Katz http://inst.eecs.berkeley.edu/~cs61c And in Conclusion, 2 Processor Control Datapath Components of a Computer PC Registers Arithmetic

More information

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

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below: QUIZ 1. Explain the meaning of the angle brackets in the declaration of v below: This is a template, used for generic programming! QUIZ 2. Why is the vector class called a container? 3. Explain how the

More information

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

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers CS 61C: Great Ideas in Computer Architecture C Arrays, Strings, More Pointers Instructor: Justin Hsia 6/20/2012 Summer 2012 Lecture #3 1 Review of Last Lecture C Basics Variables, Functions, Flow Control,

More information

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

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

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

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz CS 61C: Great Ideas in Computer Architecture Lecture 3: Pointers Krste Asanović & Randy Katz http://inst.eecs.berkeley.edu/~cs61c Agenda Pointers in C Arrays in C This is not on the test Pointer arithmetic

More information

Object oriented programming C++

Object oriented programming C++ http://uranchimeg.com Object oriented programming C++ T.Uranchimeg Prof. Dr. Email uranchimeg@must.edu.mn Power Engineering School M.EC203* -- OOP (C++) -- Lecture 07 Subjects Pointers Pointer and array

More information

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

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong This is CS50. Harvard University. Fall 2014. Cheng Gong Table of Contents News... 1 Buffer Overflow... 1 Malloc... 6 Linked Lists... 7 Searching... 13 Inserting... 16 Removing... 19 News Good news everyone!

More information

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

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan Operating Systems 2INC0 C course Pointer Advanced Dr. Ir. Ion Barosan (i.barosan@tue.nl) Containt Pointers Definition and Initilization Ponter Operators Pointer Arithmetic and Array Calling Functions by

More information

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

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018 Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory

More information

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

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

today cs3157-fall2002-sklar-lect05 1

today cs3157-fall2002-sklar-lect05 1 today homework #1 due on monday sep 23, 6am some miscellaneous topics: logical operators random numbers character handling functions FILE I/O strings arrays pointers cs3157-fall2002-sklar-lect05 1 logical

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Dynamic memory allocation

Dynamic memory allocation Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes

More information

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

Please refer to the turn-in procedure document on the website for instructions on the turn-in procedure. 1 CSE 131 Winter 2013 Compiler Project #2 -- Code Generation Due Date: Friday, March 15 th 2013 @ 11:59pm Disclaimer This handout is not perfect; corrections may be made. Updates and major clarifications

More information

A brief introduction to C programming for Java programmers

A brief introduction to C programming for Java programmers A brief introduction to C programming for Java programmers Sven Gestegård Robertz September 2017 There are many similarities between Java and C. The syntax in Java is basically

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 5 C Memory Management Lecturer PSOE Dan Garcia www.cs.berkeley.edu/~ddgarcia CS 61C L04 C Structures, Memory Management (1) 2004-09-10 Barry

More information

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

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty! Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns

More information

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

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver CS 61C: Great Ideas in Computer Architecture C Pointers Instructors: Vladimir Stojanovic & Nicholas Weaver http://inst.eecs.berkeley.edu/~cs61c/sp16 1 Agenda Pointers Arrays in C 2 Address vs. Value Consider

More information

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

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc CS61C L4 C Pointers (1) inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 C Strings, Arrays, & Malloc Albert Chae Instructor 2008-06-26 Review: C Strings A string in C is just an array

More information

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

CS 61C: Great Ideas in Computer Architecture Introduction to C CS 61C: Great Ideas in Computer Architecture Introduction to C Instructors: Vladimir Stojanovic & Nicholas Weaver http://inst.eecs.berkeley.edu/~cs61c/ 1 Agenda C vs. Java vs. Python Quick Start Introduction

More information

Singly linked lists in C.

Singly linked lists in C. Singly linked lists in C http://www.cprogramming.com/tutorial/c/lesson15.html By Alex Allain Linked lists are a way to store data with structures so that the programmer can automatically create a new place

More information

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

Slide Set 6. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng Slide Set 6 for ENCM 339 Fall 2017 Section 01 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary October 2017 ENCM 339 Fall 2017 Section 01 Slide

More information

Data Structure Series

Data Structure Series Data Structure Series This series is actually something I started back when I was part of the Sweet.Oblivion staff, but then some things happened and I was no longer able to complete it. So now, after

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

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

Professor Terje Haukaas University of British Columbia, Vancouver  C++ Programming C++ Programming C++ code is essentially a collection of statements terminated by a semicolon, such as (spaces not needed): a = b + c; Most C++ code is organized into header files and cpp files, i.e., C++

More information

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

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming Jagannath Institute of Management Sciences Lajpat Nagar BCA II Sem C Programming UNIT I Pointers: Introduction to Pointers, Pointer Notation,Decalaration and Initialization, Accessing variable through

More information

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

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 Passing arrays to functions A big topic for beginners is how to write a function that can be passed an array. A very common way of achieving this is done using pointers. This method can be seen all through

More information

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

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved. Chapter 10 Pointers and Dynamic Arrays Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic

More information

Character Strings. String-copy Example

Character Strings. String-copy Example Character Strings No operations for string as a unit A string is just an array of char terminated by the null character \0 The null character makes it easy for programs to detect the end char s[] = "0123456789";

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 5 C Memory Management Lecturer PSOE Dan Garcia www.cs.berkeley.edu/~ddgarcia CS61C L05 C Structures, Memory Management (1) 2005-01-28 The

More information

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

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng Slide Set 2 for ENCM 335 in Fall 2018 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary September 2018 ENCM 335 Fall 2018 Slide Set 2 slide

More information

Chapter 1: Object-Oriented Programming Using C++

Chapter 1: Object-Oriented Programming Using C++ Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms

More information

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

Procedures, Parameters, Values and Variables. Steven R. Bagley Procedures, Parameters, Values and Variables Steven R. Bagley Recap A Program is a sequence of statements (instructions) Statements executed one-by-one in order Unless it is changed by the programmer e.g.

More information

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

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

More information

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

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites: C Programming Code: MBD101 Duration: 10 Hours Prerequisites: You are a computer science Professional/ graduate student You can execute Linux/UNIX commands You know how to use a text-editing tool You should

More information

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

Cpt S 122 Data Structures. Course Review Midterm Exam # 1 Cpt S 122 Data Structures Course Review Midterm Exam # 1 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 1 When: Friday (09/28) 12:10-1pm Where:

More information

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

CprE 288 Introduction to Embedded Systems Exam 1 Review.  1 CprE 288 Introduction to Embedded Systems Exam 1 Review http://class.ece.iastate.edu/cpre288 1 Overview of Today s Lecture Announcements Exam 1 Review http://class.ece.iastate.edu/cpre288 2 Announcements

More information

FUNCTIONS POINTERS. Pointers. Functions

FUNCTIONS POINTERS. Pointers. Functions Functions Pointers FUNCTIONS C allows a block of code to be separated from the rest of the program and named. These blocks of code or modules are called functions. Functions can be passed information thru

More information

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

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language Introduction C++ widely-used general-purpose programming language procedural and object-oriented support strong support created by Bjarne Stroustrup starting in 1979 based on C Introduction to C++ also

More information

CS 2461: Computer Architecture I

CS 2461: Computer Architecture I Next: Pointers, Arrays, Structs... : Computer Architecture I The real fun stuff in C.. Pointers and Arrays Read Chapters 16, 18 of text Functions, Arrays, Pointers Dynamic data structures Allocating space

More information

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

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 Sample Test Paper-I Marks : 25 Time:1 Hrs. Q1. Attempt any THREE 09 Marks a) State four relational operators with meaning. b) State the use of break statement. c) What is constant? Give any two examples.

More information

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

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial A Walkthrough with Examples CMSC 212 - Spring 2009 Last modified March 22, 2009 What is gdb? GNU Debugger A debugger for several languages, including C and C++ It allows you to inspect what the program

More information

Final CSE 131B Spring 2005

Final CSE 131B Spring 2005 Login name Signature Name Student ID Final CSE 131B Spring 2005 Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 Page 7 Page 8 (27 points) (24 points) (32 points) (24 points) (32 points) (26 points) (31 points)

More information

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

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo Chapter 10 Pointers and Dynamic Arrays 1 Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic Classes, Pointers, Dynamic Arrays The this

More information

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

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3). cs3157: another C lecture (mon-21-feb-2005) C pre-processor (1). today: C pre-processor command-line arguments more on data types and operators: booleans in C logical and bitwise operators type conversion

More information

Introduction to C++ with content from

Introduction to C++ with content from Introduction to C++ with content from www.cplusplus.com 2 Introduction C++ widely-used general-purpose programming language procedural and object-oriented support strong support created by Bjarne Stroustrup

More information

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 11: Structures and Memory (yaseminb@kth.se) Overview Overview Lecture 11: Structures and Memory Structures Continued Memory Allocation Lecture 11: Structures and Memory Structures Continued Memory

More information

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors Arrays Returning arrays Pointers Dynamic arrays Smart pointers Vectors To declare an array specify the type, its name, and its size in []s int arr1[10]; //or int arr2[] = {1,2,3,4,5,6,7,8}; arr2 has 8

More information

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

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable.

More information

Arrays and Pointers in C & C++

Arrays and Pointers in C & C++ Arrays and Pointers in C & C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++,

More information