C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura

Similar documents
Lecture 05 POINTERS 1

Chapter 7. Pointers. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

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

Chapter 6 - Pointers

Pointers. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Fundamentals of Programming Session 20

C Pointers. Indirection Indirection = referencing a value through a pointer. Creating Pointers. Pointer Declarations. Pointer Declarations

C Pointers Pearson Education, Inc. All rights reserved.

C Pointers. 7.2 Pointer Variable Definitions and Initialization

by Pearson Education, Inc. All Rights Reserved.

Pointers and Strings Prentice Hall, Inc. All rights reserved.

POINTERS. Content. Pointers. Benefits of Pointers. In this chapter, you will learn:

Programming for Engineers Pointers

Fundamental of Programming (C)

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

C++ Programming Chapter 7 Pointers

A pointer is a variable just like other variable. The only difference from other variables is that it stores the memory address other variables.

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings

MYcsvtu Notes LECTURE 34. POINTERS

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

Pointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Fundamentals of Programming Session 20

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

Pointers and Strings Prentice Hall, Inc. All rights reserved.

Pointers and Strings. Adhi Harmoko S, M.Komp

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

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then

Pointer in C SHARDA UNIVERSITY. Presented By: Pushpendra K. Rajput Assistant Professor

Introduction to C. Systems Programming Concepts

Operators and Expressions:

Fundamentals of Programming Session 19

Variation of Pointers

PROGRAMMAZIONE I A.A. 2017/2018

Pointers in C. Recap: Anatomy of a Typical C Program. declarations variables functions. int main (void){ declarations; statements; return value; }

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Arrays and Pointers in C. Alan L. Cox

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

Pointers. 10/5/07 Pointers 1

... Lecture 12. Pointers

Character Array. C Programming. String. A sequence of characters The last character should be \0 that indicates the end of string 5 \0

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

Goals of this Lecture

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

Relationship between Pointers and Arrays

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

Outline Arrays Examples of array usage Passing arrays to functions 2D arrays Strings Searching arrays Next Time. C Arrays.

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Work relative to other classes

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

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

More Pointers Week 11

Content. In this chapter, you will learn:

Chapter 7 C Pointers

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

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

POINTER & REFERENCE VARIABLES

Fundamentals of Programming Session 19

IS 0020 Program Design and Software Tools

2.2 Pointers. Department of CSE

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

Data Types and Computer Storage Arrays and Pointers. K&R, chapter 5

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

More about BOOLEAN issues

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

CSC 211 Intermediate Programming. Arrays & Pointers

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Procedural programming with C

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

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

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

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Arrays and Memory Management

C Pointers. 6th April 2017 Giulio Picierro

Technical Questions. Q 1) What are the key features in C programming language?

Fundamental of Programming (C)

What is an algorithm?

Homework #3 CS2255 Fall 2012

C Characters and Strings

Variables and literals

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Arrays and Pointers. CSE 2031 Fall November 11, 2013

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

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

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

BLM2031 Structured Programming. Zeyneb KURT

Basics of Programming

CSCI-1200 Data Structures Spring 2014 Lecture 5 Pointers, Arrays, Pointer Arithmetic

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

Arrays and Pointers. CSC209: Software Tools and Systems Programming (Winter 2019) Furkan Alaca & Paul Vrbik. University of Toronto Mississauga

Programming in C - Part 2

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

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

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

CS 0449 Sample Midterm

Topics so far. Review. scanf/fscanf. How data is read 1/20/2011. All code handin sare at /afs/andrew/course/15/123/handin

Transcription:

CS 2060 Week 6

1 Pointer Variables 2 Pass-by-reference 3 const pointers 4 Pointer arithmetic 5 sizeof 6 Arrays of pointers 7 Next Time

Pointers The pointer is one of C s most powerful and important features. They are also difficult to master and hard to debug. Pointers allow us to: Effectively pass-by-reference Pass functions as arguments to functions Create dynamic data structures such as linked lists, trees

Pointers A pointer is a variable whose value is a memory address. The variable does not contain meaningful data itself, but instead points to where data is located in memory. Given the pointer (a memory address), we can dereference the pointer to read/write the value stored at that address.

Defining pointers Every data type has an associated pointer type: int count; // integer int *countptr; // pointer to an integer Variable countptr has type int *.

Defining pointers Every data type has an associated pointer type: int count; // integer int *countptr; // pointer to an integer Variable countptr has type int *. Be careful with multiple definitions on the same line: int *countptr, count;

Defining pointers Every data type has an associated pointer type: int count; // integer int *countptr; // pointer to an integer Variable countptr has type int *. Be careful with multiple definitions on the same line: int *countptr, count; Only countptr is a pointer; count is still an integer.

Defining pointers Every data type has an associated pointer type: int count; // integer int *countptr; // pointer to an integer Variable countptr has type int *. Be careful with multiple definitions on the same line: int *countptr, count; Only countptr is a pointer; count is still an integer. int *countptr, *sumptr; Both countptr and sumptr are pointers.

Initializing pointers We make a pointer point to a variable s memory address using the reference operator &: int count = 5; // integer int *countptr = &count; // pointer to an integer Variable countptr now holds the memory address of count.

Dereferencing pointers To read from / write to the value in memory, we can use the dereference operator *: int count = 5; // integer int *countptr = &count; // pointer to an integer *countptr += 5; // count now = 10 printf("%d\n", count); // outputs 10 printf("%d\n", (*countptr) ); // outputs 10 printf("%lu\n", countptr ); // outputs address

Initializing pointers It is good practice to initialize pointers. Dereferencing an uninitialized pointer may or may not crash the program, leading to hard-to-detect bugs.

Initializing pointers It is good practice to initialize pointers. Dereferencing an uninitialized pointer may or may not crash the program, leading to hard-to-detect bugs. The constant NULL is defined in stddef.h (and other standard headers) for this purpose. NULL is equal to 0. int *myptr = NULL; // initialized

Initializing pointers It is good practice to initialize pointers. Dereferencing an uninitialized pointer may or may not crash the program, leading to hard-to-detect bugs. The constant NULL is defined in stddef.h (and other standard headers) for this purpose. NULL is equal to 0. int *myptr = NULL; // initialized Dereferencing a NULL pointer will definitely crash the program!

Inspecting variable addresses #include<stdio.h> int main() { int a = 5; int b = 10; int *aptr = &a; int *bptr = &b; printf("%lu\n",aptr); printf("%lu\n",bptr);

Inspecting variable addresses #include<stdio.h> int main() { int array[4]; for ( int i = 0; i < 4; i++ ) { printf("%lu ",&array[i]); puts("");

Reference/dereference operator precedence We have to be careful to make sure we are referencing / dereferencing the correct address. int array[5]; int *ptr = &array[1]; Is & applied to array or array[1]?

Reference/dereference operator precedence We have to be careful to make sure we are referencing / dereferencing the correct address. int array[5]; int *ptr = &array[1]; Is & applied to array or array[1]? The & is applied to array[1], because [] has higher precedence than &.

Passing arguments by reference with pointers With pointers we can implement pass-by-reference: int myfn( float *valueptr ); The function myfn can modify the value pointed to by valueptr by dereferencing the pointer.

Pass-by-value example #include <stdio.h> int cubebyvalue( int n ); int main() { int number = 5; printf("number is %d\n", number ); number = cubebyvalue( number ); printf("number is %d\n", number ); int cubebyvalue( int n ) { return n * n * n;

Pass-by-reference example #include <stdio.h> void cubebyreference( int *nptr ); int main() { int number = 5; printf("number is %d\n", number ); cubebyreference( &number ); printf("number is %d\n", number ); void cubebyreference( int *nptr ) { *nptr = *nptr * *nptr * *nptr;

Pass-by-reference example #include <stdio.h> void cubebyreference( int *nptr ); int main() { int number = 5; printf("number is %d\n", number ); cubebyreference( &number ); printf("number is %d\n", number ); void cubebyreference( int *nptr ) { // put pointer dereference in parentheses // to make code easier to read *nptr = (*nptr) * (*nptr) * (*nptr);

Pointers and arrays In the function header, a pointer and a one-dimensional array are interchangeable. float sumarray( float array[] ); float sumarray( float *array ); These two function headers are equivalent.

Pointers and strings It is possible to assign a string to a pointer: char *stringptr = "hello!"; char stringarray[] = "hello!"; These are almost equivalent, but there is a difference to be discussed later.

const pointers Using the const keyword, we can restrict the code from modifying the data pointed to by the pointer. int data = 10; const int* dataptr = &data; int datacopy = *dataptr; // allowed *dataptr += 1; // not allowed

const pointers We can also use const to restrict the code from modifying the pointer itself. In this case, the const comes after the *. int data = 10; int * const dataptr = &data; int datacopy = *dataptr; // allowed *dataptr += 1; // allowed dataptr += 1; // not allowed

const pointers Using both constructions, we get a pointer where neither the address nor the data can be changed. int data = 10; const int * const dataptr = &data; int datacopy = *dataptr; // allowed *dataptr += 1; // not allowed dataptr += 1; // not allowed

Applications of const pointers #include <stdio.h> #include <ctype.h> void converttouppercase( char *sptr ); int main() { char string[] = "Hello, World!"; puts(string); converttouppercase(string); puts(string); void converttouppercase( char *sptr ) { while ( *sptr!= \0 ) { // loop until null terminator *sptr = toupper(*sptr); // convert to uppercase ++sptr; // increment pointer

Applications of const pointers #include <stdio.h> #include <ctype.h> // printstring should not change input data void printstring( const char *sptr ); int main() { char string[] = "Hello, World!"; printstring(string); void printstring( const char *sptr ) { while ( *sptr!= \0 ) { // loop until null terminator putchar( *sptr ); // print character ++sptr; // increment pointer -- will point to next character

Applications of const pointers #include <stdio.h> #include <ctype.h> void exponents( const float *input, float *square, float *cube ); int main() { float value = 10.f; //.f indicates float float square; float cube; exponents( &value, &square, &cube ); printf("%f %f %f\n",value, square, cube); void exponents( const float *input, float *square, float *cube ) { *square = (*input) * (*input); *cube = (*input) * (*input) * (*input);

Pointer arithmetic operators A pointer is simply an integer: A memory address Number of bytes from the beginning of memory So, we can do integer arithmetic (add or subtract) on pointers. Allowed operations: pointer++ pointer-- pointer + integer pointer - integer pointer - pointer

Pointing to an array Pointer arithmetic is useful when iterating over an array. First we need to make our pointer point to the array: int array[5] = { 0, 1, 2, 3, 4 ; int *ptr = array; // --- OR --- int *ptr = &array[0];

Pointer arithmetic example Now we can iterate over the array by incrementing the pointer: int array[5] = { 0, 1, 2, 3, 4 ; // initialize pointer to first element of array int *ptr = array; // increments pointer // will now point to second element ptr++; // print second element (prints 1) printf("%d\n", (*ptr) );

Pointer arithmetic example Now we can iterate over the array by incrementing the pointer: int array[5] = { 0, 1, 2, 3, 4 ; for ( int *ptr = array; ptr!= array+5; ptr++ ) { printf("%d\n", (*ptr) );

Pointer arithmetic example We can similarly use += to increment by larger step sizes: int array[5] = { 0, 1, 2, 3, 4 ; for ( int *ptr = array; ptr!= array+5; ptr+=2 ) { printf("%d\n", (*ptr) ); What s the error here?

Pointer arithmetic example We can similarly use += to increment by larger step sizes: int array[5] = { 0, 1, 2, 3, 4 ; for ( int *ptr = array; ptr < array+5; ptr+=2 ) { printf("%d\n", (*ptr) ); Need to use < instead of!=.

Pointer arithmetic example Using decrement, we can iterate over the array backward: int array[5] = { 0, 1, 2, 3, 4 ; for ( int *ptr = array+4; ptr >= array; ptr-- ) { printf("%d\n", (*ptr) );

Pointer arithmetic example Decrementing with a greater step size: int array[5] = { 0, 1, 2, 3, 4 ; for ( int *ptr = array+4; ptr >= array; ptr -= 2 ) { printf("%d\n", (*ptr) );

Pointer arithmetic example With a while loop: int array[5] = { 0, 1, 2, 3, 4 ; int *ptr = array; while ( ptr < array+5 ) printf( "%d\n", (*ptr++) );

Reference/dereference operator precedence Operators Associativity () [] ++ (postfix) -- (postfix) left to right + - ++ (prefix) -- (prefix)! * & (type) right to left + / % left to right < <= > >= left to right... Table: Operator precedence

Reference/dereference operator precedence #include<stdio.h> int main() { int data[5] = { 10, 20, 30, 40, 50 ; int *dataptr = data; printf("%d ",*dataptr++); printf("%d ",*dataptr); What does this print?

Reference/dereference operator precedence #include<stdio.h> int main() { int data[5] = { 10, 20, 30, 40, 50 ; int *dataptr = data; printf("%d ",*dataptr++); printf("%d ",*dataptr); Outputs 10 20. The ++ is applied to the pointer after the first print.

Reference/dereference operator precedence #include<stdio.h> int main() { int data[5] = { 10, 20, 30, 40, 50 ; int *dataptr = data; printf("%d ",*++dataptr); printf("%d ",*dataptr); What does this print?

Reference/dereference operator precedence #include<stdio.h> int main() { int data[5] = { 10, 20, 30, 40, 50 ; int *dataptr = data; printf("%d ",*++dataptr); printf("%d ",*dataptr); Outputs 20 20. The ++ is applied to the pointer before the first print.

Reference/dereference operator precedence #include<stdio.h> int main() { int data[5] = { 10, 20, 30, 40, 50 ; int *dataptr = data; printf("%d ",++*dataptr); printf("%d ",*dataptr); What does this print?

Reference/dereference operator precedence #include<stdio.h> int main() { int data[5] = { 10, 20, 30, 40, 50 ; int *dataptr = data; printf("%d ",++*dataptr); printf("%d ",*dataptr); Outputs 11 11. The ++ is applied to the data pointed to by the pointer before the first print.

Reference/dereference operator precedence #include<stdio.h> int main() { int data[5] = { 10, 20, 30, 40, 50 ; int *dataptr = data; printf("%d ",(*dataptr)++); printf("%d ",*dataptr); What does this print?

Reference/dereference operator precedence #include<stdio.h> int main() { int data[5] = { 10, 20, 30, 40, 50 ; int *dataptr = data; printf("%d ",(*dataptr)++); printf("%d ",*dataptr); Outputs 10 11. The ++ is applied to the data pointed to by the pointer after the first print.

Pointer arithmetic example We can subtract pointers: int array[5] = { 0, 1, 2, 3, 4 ; int *ptr1 = array; int *ptr2 = array+4; int x = ptr2 - ptr1; What will x equal here? Why is this useful?

Pointer arithmetic example We can subtract pointers: int array[5] = { 0, 1, 2, 3, 4 ; int *ptr1 = array; int *ptr2 = array+4; // x will equal 4 int x = ptr2 - ptr1; This tells us the number of elements from ptr1 to ptr2.

Pointer arithmetic example We can subtract pointers: int array[5] = { 0, 1, 2, 3, 4 ; int *ptr = array; while ( (*ptr) < 3 ) ptr++; int x = ptr - array; What will x equal here?

Pointer arithmetic example We can subtract pointers: int array[5] = { 0, 1, 2, 3, 4 ; int *ptr = array; while ( (*ptr) < 3 ) ptr++; int x = ptr - array; x = 3 Finds index of first value in array >= 3.

Comparing pointers As seen in the previous examples, we can compare pointers using >, <, etc. The comparison operator on pointers will compare memory addresses. int array[5] = { 0, 1, 2, 3, 4 ; int *start = array; int *end = array+5; int *ptr = start; while ( ptr < end ) printf("%d\n", (*ptr++) );

void * pointers A special type of pointer is a void * pointer. This pointer has no data type it can point to any kind of data. int array[5] = { 0, 1, 2, 3, 4 ; void *ptr = array;

void * pointers We are not allowed to dereference a void * pointer. The compiler would not know what data type to produce. int array[5] = { 0, 1, 2, 3, 4 ; void *ptr = array; char c = (*ptr); // not allowed

void * pointers Instead, we need to cast the pointer to some data type: int array[5] = { 0, 1, 2, 3, 4 ; void *ptr = array; char *charptr = (char*)ptr; char c = (*charptr); // allowed What does this code do?

void * pointers Instead, we need to cast the pointer to some data type: int array[5] = { 0, 1, 2, 3, 4 ; void *ptr = array; char *charptr = (char*)ptr; char c = (*charptr); // allowed int is 4 bytes char is 1 byte char c will equal the first byte array[0].

sizeof sizeof tells us the size in bytes of an array (or any other data type). int array[10]; size_t nbytes = sizeof(array); What will nbytes equal? size t is an unsigned long int (64-bit non-negative integer).

sizeof sizeof tells us the size in bytes of an array (or any other data type). int array[10]; size_t nbytes = sizeof(array); nbytes is equal to 10 4 bytes = 40 bytes.

sizeof sizeof tells us the size in bytes of an array (or any other data type). double array[10]; size_t nbytes = sizeof(array); What will nbytes equal?

sizeof sizeof can also be called on basic data types to find out their size it varies according to platform and compiler. size_t nbytes = sizeof(double); // equals to 8 Or we can call sizeof on a normal variable: double a = 10.; //. means double size_t nbytes = sizeof(a); // equals to 8

sizeof sizeof tells us the size in bytes of an array (or any other data type). double array[10]; size_t nbytes = sizeof(array); A double is 64-bit (8 bytes). nbytes is equal to 10 8 bytes = 80 bytes.

sizeof There is an exception to the rule about sizeof on arrays. When an array is passed to a function, the receving function does not know the size of the array. What does sizeof return in this case?

sizeof #include <stdio.h> void myfn( int array[] ) { printf("sizeof(array) in function: %lu\n",sizeof(array)); int main() { int array[10]; printf("sizeof(array) where it is defined: %lu\n",sizeof(array)); myfn( array );

sizeof #include <stdio.h> void myfn( int array[] ) { printf("sizeof(array) in function: %lu\n",sizeof(array)); int main() { int array[10]; printf("sizeof(array) where it is defined: %lu\n",sizeof(array)); myfn( array ); In main, sizeof returns 40 In myfn, sizeof returns 8 Why?

sizeof #include <stdio.h> void myfn( int *array ) { printf("sizeof(array) in function: %lu\n",sizeof(array)); int main() { int array[10]; printf("sizeof(array) where it is defined: %lu\n",sizeof(array)); myfn( array ); int array[] is equivalent to int *array In the function, sizeof returns the size of the pointer Memory address is 64 bits = 8 bytes on this machine.

Arrays of pointers Sometimes it is useful to make an array of pointers: const char *suit[4] = { "Hearts", "Diamonds", "Clubs", "Spades" ; The array contains four pointers. The pointers point to character arrays.

Arrays of pointers Sometimes it is useful to make an array of pointers: const char *suit[4] = { "Hearts", "Diamonds", "Clubs", "Spades" ; Why is this preferred over creating a 2D array of characters?

Arrays of pointers Sometimes it is useful to make an array of pointers: const char *suit[4] = { "Hearts", "Diamonds", "Clubs", "Spades" ; A 2D array would need to have a fixed size Would need to be as big as the longest string Would waste space.

Next Time Homework 6 due Wednesday, March 2, 11:55 PM. No class Thursday Next week: function pointers, midterm review, exam