Pointers. March 19, 2012

Similar documents
arrays C Programming Language - Arrays

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

How To Write Portable Programs In C

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Sources: On the Web: Slides will be available on:

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

6.S096 Lecture 1 Introduction to C

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Informatica e Sistemi in Tempo Reale

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

The C Programming Language course syllabus associate level

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Lecture 12 Doubly Linked Lists (with Recursion)

5 Arrays and Pointers

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

Keil C51 Cross Compiler

1 Abstract Data Types Information Hiding

C++ Programming Language

1 Description of The Simpletron

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

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

So far we have considered only numeric processing, i.e. processing of numeric data represented

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

System Calls and Standard I/O

Record Storage and Primary File Organization

The programming language C. sws1 1

Let s put together a Manual Processor

Implementation Aspects of OO-Languages

B.Sc.(Computer Science) and. B.Sc.(IT) Effective From July 2011

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

Pseudo code Tutorial and Exercises Teacher s Version

Lecture 7: Machine-Level Programming I: Basics Mohamed Zahran (aka Z)

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Parallel and Distributed Computing Programming Assignment 1

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

1. Relational database accesses data in a sequential form. (Figures 7.1, 7.2)

Introduction to Information Security

Lecture 22: C Programming 4 Embedded Systems

Microcontroller Systems. ELET 3232 Topic 8: Slot Machine Example

C Interview Questions

CS61: Systems Programing and Machine Organization

6. Standard Algorithms

X86-64 Architecture Guide

Parameter Passing. Parameter Passing. Parameter Passing Modes in Fortran. Parameter Passing Modes in C

3/13/2012. Writing Simple C Programs. ESc101: Decision making using if-else and switch statements. Writing Simple C Programs

Comp 255Q - 1M: Computer Organization Lab #3 - Machine Language Programs for the PDP-8

Module 816. File Management in C. M. Campbell 1993 Deakin University

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

Objective-C Tutorial

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

Number Representation

7.1 Our Current Model

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

The AVR Microcontroller and C Compiler Co-Design Dr. Gaute Myklebust ATMEL Corporation ATMEL Development Center, Trondheim, Norway

Introduction to Java

Linux Driver Devices. Why, When, Which, How?

C PROGRAMMING FOR MATHEMATICAL COMPUTING

Memory Allocation. Static Allocation. Dynamic Allocation. Memory Management. Dynamic Allocation. Dynamic Storage Allocation

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Unit Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

C Dynamic Data Structures. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

Binary Adders: Half Adders and Full Adders

CSI 402 Lecture 13 (Unix Process Related System Calls) 13 1 / 17

(Refer Slide Time: 00:01:16 min)

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

1 The Java Virtual Machine

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

In this Chapter you ll learn:

1. The First Visual C++ Program

Chapter 5 Instructor's Manual

Efficient representation of integer sets

Lecture 11 Array of Linked Lists

PROBLEMS (Cap. 4 - Istruzioni macchina)

CP Lab 2: Writing programs for simple arithmetic problems

Lecture 2. Binary and Hexadecimal Numbers

Passing 1D arrays to functions.

CS 106 Introduction to Computer Science I

An overview of FAT12

Example 1/24. Example

Embedded C Programming

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

recursion, O(n), linked lists 6/14

Chapter 4: Computer Codes

Semantic Analysis: Types and Type Checking

Crash Dive into Python

Session 2: MUST. Correctness Checking

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Streaming Lossless Data Compression Algorithm (SLDC)

File Handling. What is a file?

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Computer Organization and Architecture

LINKED DATA STRUCTURES

C Programming Tutorial

Chapter 7D The Java Virtual Machine

Transcription:

Pointers March 19, 2012

Outline 1 Pointers 2 Pointer Arithmetic 3 Arrays and Pointers 4 Passing Pointers to Functions

Pointers Pointers are variables, which contain the address of some other variables. Declaration: datatype *pointername; e.g. long * ptra; The type of a pointer depends on the type of the variable it points to. Every pointer points to some data type.

Sizes of basic data types All data is stored in memory. But different data types occupy different amount of memory. The sizeof() operator in C can be used to determine the number of bytes occupied by each data type.

Sizes of basic data types All data is stored in memory. But different data types occupy different amount of memory. The sizeof() operator in C can be used to determine the number of bytes occupied by each data type. For example, on some machine you may have sizeof(int) = 4 sizeof(float) = 4 sizeof(double) = 8

Sizes of basic data types All data is stored in memory. But different data types occupy different amount of memory. The sizeof() operator in C can be used to determine the number of bytes occupied by each data type. For example, on some machine you may have sizeof(int) = 4 sizeof(float) = 4 sizeof(double) = 8 These numbers are Not the same for all machines. You should use the sizeof() operator instead of assuming the value.

A Sample Program #include <stdio.h> 0 1 2 3 4 X c int main() { int n; char c; int *ptrn; 2 32 1. c= X ; n=15; ptrn=&n; Memory Layout (Bytes) } return 0;

0 1 2 3 4 X c. 20 0 n 21 0 22 0 23 15. 2 32 1 #include <stdio.h> int main() { char c; int n; int *ptrn; } c= X ; n=15; ptrn=&n; return 0;

. 4 X c. 20 0 n 21 0 22 0 23 15. 8003 0 ptrn 8003 0 8003 0 8003 20 2 32 1. #include <stdio.h> int main() { int n; char c; int *ptrn; } c= X ; n=15; //address of n //sizeof(ptrn) = 4 ptrn=&n; return 0; sizeof(ptrn) = 4 bytes = 32 bits, since we have 2 32 byte addresses.

Address Operations There are two unary operations to consider. The * operator: If ptra is a pointer variable, then ptra gives you the content of the location pointed to by ptr.

Address Operations There are two unary operations to consider. The * operator: If ptra is a pointer variable, then ptra gives you the content of the location pointed to by ptr. The & operator: If v is a variable, then &v is the address of the variable.

Address Operations There are two unary operations to consider. The * operator: If ptra is a pointer variable, then ptra gives you the content of the location pointed to by ptr. The & operator: If v is a variable, then &v is the address of the variable. *pointer pointer & data data

Address Operations There are two unary operations to consider. The * operator: If ptra is a pointer variable, then ptra gives you the content of the location pointed to by ptr. The & operator: If v is a variable, then &v is the address of the variable. *pointer pointer & data data In the previous code, what is *ptrn?

Address Operations There are two unary operations to consider. The * operator: If ptra is a pointer variable, then ptra gives you the content of the location pointed to by ptr. The & operator: If v is a variable, then &v is the address of the variable. *pointer pointer & data data In the previous code, what is *ptrn? Caution: Declaration of a pointer also uses *.

Outline 1 Pointers 2 Pointer Arithmetic 3 Arrays and Pointers 4 Passing Pointers to Functions

Pointer Arithmetic Problem: How do we do relative addressing? (for example, next element in an integer array)

Pointer Arithmetic Problem: How do we do relative addressing? (for example, next element in an integer array) C allows you to perform some arithmetic operations on pointers. (Not every operation is allowed.) Consider <datatype> *ptrn; //datatype can be int, long, etc.

Pointer Arithmetic Problem: How do we do relative addressing? (for example, next element in an integer array) C allows you to perform some arithmetic operations on pointers. (Not every operation is allowed.) Consider <datatype> *ptrn; //datatype can be int, long, etc.

Pointer Arithmetic Problem: How do we do relative addressing? (for example, next element in an integer array) C allows you to perform some arithmetic operations on pointers. (Not every operation is allowed.) Consider <datatype> *ptrn; //datatype can be int, long, etc. Unary Pointer Arithmetic Operators

Pointer Arithmetic Problem: How do we do relative addressing? (for example, next element in an integer array) C allows you to perform some arithmetic operations on pointers. (Not every operation is allowed.) Consider <datatype> *ptrn; //datatype can be int, long, etc. Unary Pointer Arithmetic Operators Operator ++: Adds sizeof(datatype) number of bytes to pointer, so that it points to the next entry of the datatype.

Pointer Arithmetic Problem: How do we do relative addressing? (for example, next element in an integer array) C allows you to perform some arithmetic operations on pointers. (Not every operation is allowed.) Consider <datatype> *ptrn; //datatype can be int, long, etc. Unary Pointer Arithmetic Operators Operator ++: Adds sizeof(datatype) number of bytes to pointer, so that it points to the next entry of the datatype. Operator : Subtracts sizeof(datatype) number of bytes to pointer, so that it points to the next entry of the datatype.

Pointer Arithmetic - Example 1 #include <stdio.h> int main() { int *ptrn; long *ptrlng; ptrn++; ptrlng++; //increments by sizeof(int) (4 bytes) //increments by sizeof(long) (8 bytes) } return 0;

Pointer Arithmetic - II Pointers and integers are not interchangeable. (except for 0.) We will have to treat arithmetic between a pointer and an integer, and arithmetic between two pointers, separately.

Pointer Arithmetic - II Pointers and integers are not interchangeable. (except for 0.) We will have to treat arithmetic between a pointer and an integer, and arithmetic between two pointers, separately. Suppose you have a pointer to a long. long *ptrlng;

Pointer Arithmetic - II Pointers and integers are not interchangeable. (except for 0.) We will have to treat arithmetic between a pointer and an integer, and arithmetic between two pointers, separately. Suppose you have a pointer to a long. long *ptrlng; Binary Operations between a pointer and an integer

Pointer Arithmetic - II Pointers and integers are not interchangeable. (except for 0.) We will have to treat arithmetic between a pointer and an integer, and arithmetic between two pointers, separately. Suppose you have a pointer to a long. long *ptrlng; Binary Operations between a pointer and an integer 1 ptrlng+n is valid, if n is an integer. The result is the following byte address ptrlng + n*sizeof(long) and not ptrlng + n. It advances the pointer by n number of longs.

Pointer Arithmetic - II Pointers and integers are not interchangeable. (except for 0.) We will have to treat arithmetic between a pointer and an integer, and arithmetic between two pointers, separately. Suppose you have a pointer to a long. long *ptrlng; Binary Operations between a pointer and an integer 1 ptrlng+n is valid, if n is an integer. The result is the following byte address ptrlng + n*sizeof(long) and not ptrlng + n. It advances the pointer by n number of longs. 2 ptrlng-n is similar.

Pointer Arithmetic - III Consider two pointers ptr1 and ptr2 which point to the same type of data. <datatype> *ptr1, *ptr2;

Pointer Arithmetic - III Consider two pointers ptr1 and ptr2 which point to the same type of data. <datatype> *ptr1, *ptr2;

Pointer Arithmetic - III Consider two pointers ptr1 and ptr2 which point to the same type of data. <datatype> *ptr1, *ptr2; Binary operations between two Pointers

Pointer Arithmetic - III Consider two pointers ptr1 and ptr2 which point to the same type of data. <datatype> *ptr1, *ptr2; Binary operations between two Pointers 1 Surprise: Adding two pointers together is not allowed!

Pointer Arithmetic - III Consider two pointers ptr1 and ptr2 which point to the same type of data. <datatype> *ptr1, *ptr2; Binary operations between two Pointers 1 Surprise: Adding two pointers together is not allowed! 2 ptr1 - ptr 2 is allowed, as long as they are pointing to elements of the same array. The result is ptr1 - ptr2 sizeof(datatype) In other settings, this operation is undefined (may or may not give the correct answer).

Pointer Arithmetic - III Consider two pointers ptr1 and ptr2 which point to the same type of data. <datatype> *ptr1, *ptr2; Binary operations between two Pointers 1 Surprise: Adding two pointers together is not allowed! 2 ptr1 - ptr 2 is allowed, as long as they are pointing to elements of the same array. The result is ptr1 - ptr2 sizeof(datatype) In other settings, this operation is undefined (may or may not give the correct answer). Why all these special cases? These rules for pointer arithmetic are intended to handle addressing inside arrays correctly.

Pointer Arithmetic - IV If we can subtract a pointer from another, all the relational operations can be supported! Logical Operations on Pointers 1 ptr1 > ptr2 is the same as ptr1 - ptr2 > 0, 2 ptr1 = ptr2 is the same as ptr1 - ptr2 = 0, 3 ptr1 < ptr2 is the same as ptr1 - ptr2 < 0, 4 and so on.

Outline 1 Pointers 2 Pointer Arithmetic 3 Arrays and Pointers 4 Passing Pointers to Functions

Arrays and Pointers Array names essentially are pointers. Array elements are stored in contiguous (consecutive) locations in memory. For example, consider int arr[10]; 1 arr is a pointer to the first element of the array.

Arrays and Pointers Array names essentially are pointers. Array elements are stored in contiguous (consecutive) locations in memory. For example, consider int arr[10]; 1 arr is a pointer to the first element of the array. 2 That is, *arr is the same as arr[0].

Arrays and Pointers Array names essentially are pointers. Array elements are stored in contiguous (consecutive) locations in memory. For example, consider int arr[10]; 1 arr is a pointer to the first element of the array. 2 That is, *arr is the same as arr[0]. 3 arr+i is a pointer to arr[i]. (arr+i is equivalent to arr+i*sizeof(int).)

Arrays and Pointers Array names essentially are pointers. Array elements are stored in contiguous (consecutive) locations in memory. For example, consider int arr[10]; 1 arr is a pointer to the first element of the array. 2 That is, *arr is the same as arr[0]. 3 arr+i is a pointer to arr[i]. (arr+i is equivalent to arr+i*sizeof(int).) 4 *(arr+i), is equal to arr[i].

Arrays and Pointers Array names essentially are pointers. Array elements are stored in contiguous (consecutive) locations in memory. For example, consider int arr[10]; 1 arr is a pointer to the first element of the array. 2 That is, *arr is the same as arr[0]. 3 arr+i is a pointer to arr[i]. (arr+i is equivalent to arr+i*sizeof(int).) 4 *(arr+i), is equal to arr[i]. 5 Question: What is &arr[i] equivalent to?

Arrays and Pointers - Figure.. 40 arr[0] = *arr = *(arr+0) 41 42 43 44 arr[1] = *(arr+1) 45 46 47 48 arr[2] = *(arr+2) 49 50 51 int arr[3];..

Outline 1 Pointers 2 Pointer Arithmetic 3 Arrays and Pointers 4 Passing Pointers to Functions

Passing Pointers to Functions Since pointers are also variables, they can be passed As input parameters to functions As return values from functions

Passing Pointers - Reason 1 Why do we pass pointer variables to functions? Recall the swap function which took input integers. This function was unable to swap the variables inside main().

Passing Pointers - Reason 1 Why do we pass pointer variables to functions? Recall the swap function which took input integers. This function was unable to swap the variables inside main(). Suppose we want a swap function which is able to swap arguments inside the caller. Main idea: Pass pointers!!

A Swap Program #include <stdio.h> //Swap the contents of locations pointed to by the //input pointers void swap(int *pa, int *pb) { int temp; } temp = *pb; *pb = *pa; *pa = temp; return; int main() { int a = 1, b = 2; int *ptra = &a; int *ptrb = &b; printf( a=%d b=%d, a, b); swap (ptra, ptrb); //equivalently, swap(&a, &b); } //a and b would now be swapped printf( a=%d b=%d, a, b); return 0; When swap(pa, pb) is called, the value of the pointers is copied to the function. The value of the pointers is the address of a and b, respectively.

0 1 2 3 20 pa 4 5 6 7 30 pb 8 9 10 11 2 temp. 20 21 22 23 1 a. 30 31 32 33 2 b. 20 ptra 30 ptrb #include <stdio.h> void swap(int *pa, int *pb) { int temp; temp = *pb; *pb = *pa; *pa = temp; } int main() { int a = 1, b = 2; int *ptra = &a; int *ptrb = &b; swap (ptra, ptrb);

0 1 2 3 20 pa 4 5 6 7 30 pb 8 9 10 11 2 temp. 20 21 22 23 1 a. 30 31 32 33 1 b. 20 ptra 30 ptrb #include <stdio.h> void swap(int *pa, int *pb) { int temp; temp=*pb; *pb = *pa; *pa = temp; } int main() { int a = 1, b = 2; int *ptra = &a; int *ptrb = &b; swap (ptra, ptrb);

0 1 2 3 20 pa 4 5 6 7 30 pb 8 9 10 11 2 temp. 20 21 22 23 2 a. 30 31 32 33 1 b. 20 ptra 30 ptrb #include <stdio.h> void swap(int *pa, int *pb) { int temp; temp=*pb; *pb = *pa; *pa = temp; } int main() { int a = 1, b = 2; int *pa = &a; int *pb = &b; swap (pa, pb);

scanf and printf If we want to modify data in the caller, then we pass address of the variables. We can see this in the difference between printf and scanf.

scanf and printf If we want to modify data in the caller, then we pass address of the variables. We can see this in the difference between printf and scanf.

scanf and printf If we want to modify data in the caller, then we pass address of the variables. We can see this in the difference between printf and scanf. scanf scanf( %d, &n); scanf needs to change the content of n. This can be done by passing the address of n.

scanf and printf If we want to modify data in the caller, then we pass address of the variables. We can see this in the difference between printf and scanf. scanf scanf( %d, &n); scanf needs to change the content of n. This can be done by passing the address of n.

scanf and printf If we want to modify data in the caller, then we pass address of the variables. We can see this in the difference between printf and scanf. scanf scanf( %d, &n); scanf needs to change the content of n. This can be done by passing the address of n. printf printf( %d,n); printf does not need to change the content of n.

Passing arrays to functions We have already seen that we can pass arrays as input to functions. We also have seen that arrays are essentially pointers. We can pass pointers, where arrays are expected, and vice versa!

Passing arrays to functions #include <stdio.h> //Count number of elements in an integer array, //until the first -1 int num_elts(int *a) { int *p; p = a; while(*p!= -1){ p++; } } return p-a; int main() { int arr[] = {1, 2, 3, -1}; printf("%d", num_elts(arr)); //Passing array as pointer return 0; }

Schematic Diagram of num elts arr 1 2 3-1 p

Schematic Diagram of num elts arr 1 2 3-1 p

Schematic Diagram of num elts arr 1 2 3-1 p

Schematic Diagram of num elts arr 1 2 3-1 p p-arr = 3

Schematic Diagram of num elts arr 1 2 3-1 p If we changed the call to the following line, num elts(arr+1); the result is 2, since the num elts will search in the subarray {2,3,-1}.

Passing Pointers to Functions - Another Reason Passing a pointer to data, instead of passing the value of the data can be much faster. This is used to reduce the slowdown due to function calling. The decision to do this must be taken with care.

Common Mistakes in Pointer Programs Programming with pointers has to be done with care. Common mistakes include 1 Crossing array boundaries - Suppose an array has 10 elements, and arr is pointing to the first element. If you do *(arr-1), or *(arr+11), you might get unpredictable behaviour. 2 Dangling Pointers - pointers that point to data that is not meaningful - for example, using a pointer without initializing it.

Debugging Pointer Programs If there is an error in a program using pointers, when executing, you will most probably get Segmentation Fault. There are several ways to find the error. 1 Go through the code carefully and see if you can locate the bug. (perfect!) 1 1 Some material in these slides has been taken from course notes by Arnab Bhattacharya.

Debugging Pointer Programs If there is an error in a program using pointers, when executing, you will most probably get Segmentation Fault. There are several ways to find the error. 1 Go through the code carefully and see if you can locate the bug. (perfect!) 2 Use a debugger like gdb to debug the code and step through the execution to locate the error. Examine the memory contents when you debug. 1 1 Some material in these slides has been taken from course notes by Arnab Bhattacharya.

Debugging Pointer Programs If there is an error in a program using pointers, when executing, you will most probably get Segmentation Fault. There are several ways to find the error. 1 1 Go through the code carefully and see if you can locate the bug. (perfect!) 2 Use a debugger like gdb to debug the code and step through the execution to locate the error. Examine the memory contents when you debug. 3 Insert printf statements to pinpoint where the code crashes. (When doing so, make sure to put \n at the end of the message - it might not print otherwise!) 1 Some material in these slides has been taken from course notes by Arnab Bhattacharya.

Debugging using printf statements - Example void merge_p(int *s, int *t, int *result, int size_s, int size_t) { int *p = s; int *q = t; printf("reached Point 0\n"); } while(p-s<size_s && q-t<size_t){ //... } printf("reached Point 1\n"); if(p-s < size_s){ while( p-s < size_s) { //... } }else if(q-t < size_t){ while( q-t < size_t) { //... } } printf("reached Point 2\n"); return;