Lecture 9 - Pointers 1

Similar documents
Lecture 05 POINTERS 1

MYcsvtu Notes LECTURE 34. POINTERS

Chapter 6 - Pointers

Fundamentals of Programming Session 20

C++ Programming Chapter 7 Pointers

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

Programming for Engineers Pointers

by Pearson Education, Inc. All Rights Reserved.

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

C Pointers Pearson Education, Inc. All rights reserved.

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

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

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

Tutorial 10 Pointers in C. Shuyue Hu

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

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

Lecture 4. Default Arguments. Set defaults in function prototype. int myfunction( int x = 1, int y = 2, int z = 3 );

Pointers. 10/5/07 Pointers 1

More Pointers Week 11

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

Computer Programming Lecture 12 Pointers

Programación de Computadores. Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana

... Lecture 12. Pointers

Content. In this chapter, you will learn:

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

Relationship between Pointers and Arrays

CSC 211 Intermediate Programming. Arrays & Pointers

Introduction to Scientific Computing and Problem Solving

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

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

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

Fundamentals of Programming Session 20

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings

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

C Pointers. 7.2 Pointer Variable Definitions and Initialization

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

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

Slides adopted from T. Ferguson Spring 2016

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

Binary Representation. Decimal Representation. Hexadecimal Representation. Binary to Hexadecimal

Decimal Representation

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples.

Lab 3. Pointers Programming Lab (Using C) XU Silei

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

Chapter 7 C Pointers

What is an algorithm?

Fundamental of Programming (C)

C++ for Engineers and Scientists. Third Edition. Chapter 12 Pointers

Pointers and Strings Chapters 10, Pointers and Arrays (10.3) 3.2 Pointers and Arrays (10.3) An array of ints can be declared as

BBM 102 Introduction to Programming II

Sir Syed University of Engineering and Technology. Computer Programming & Problem Solving ( CPPS ) Pointers. Chapter No 7

COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR. VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS

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

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

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

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

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Chapter 8. Arrays, Addresses, and Pointers : Structured Programming Structured Programming 1

Exercise 3 / Ch.7. Given the following array, write code to initialize all the elements to 0: int ed[100]; Hint: It can be done two different ways!

Pointers as Arguments

ESc101: Pointers and Arrays

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

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

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Pointers and Strings. Adhi Harmoko S, M.Komp

Fundamentals of Programming. Lecture 14 Hamed Rasifard

Week 3: Pointers (Part 2)

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

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

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

Lecture 3. More About C

PROGRAMMAZIONE I A.A. 2017/2018

Lecture 23: Pointer Arithmetic

Problem # 1. calculate the grade. Allow a student the next grade if he/she needs only 0.5 marks to obtain the next grade. Use else-if construction.

CSCI 2212: Intermediate Programming / C Review, Chapters 10 and 11

0 vs NULL // BBM 101. Introduction to Programming I. Lecture #12 C Pointers & Strings

The C language. Introductory course #1

C++ for Java Programmers

Programming and Data Structures

upper and lower case English letters: A-Z and a-z digits: 0-9 common punctuation symbols special non-printing characters: e.g newline and space.

C-LANGUAGE CURRICULAM

[0569] p 0318 garbage

IS 0020 Program Design and Software Tools

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

ESC101N Fundamentals of Computing

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

Fundamentals of Programming

Computer Programming Unit 3

EXAMINATION FOR THE BSC (HONS) INFORMATION SYSTEMS; BSC (HONS) INFORMATION TECHNOLOGY & BSC (HONS) COMPUTER SCIENCE; YEAR 1

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

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

Problem Solving and 'C' Programming

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

POINTER & REFERENCE VARIABLES

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

Variation of Pointers

A Fast Review of C Essentials Part I

Transcription:

Lecture 9 - Pointers 1

Outline Introduction Pointer Variable Definitions and Initialization Pointer Operators Calling Functions by Reference Pointer Expressions and Pointer Arithmetic Relationship between Pointers and Arrays Arrays of Pointers 2

Introduction Pointer is the address (i.e. a specific memory location) of an object. It can refer to different objects at different times. Pointers are used in C programs for a variety of purposes: To return more than one value from a function (using pass by reference) To create and process strings To manipulate the contents of arrays and structures To construct data structures whose size can grow or shrink dynamically 3

Pointer Variable Definitions and Initialization Pointer variables Contain memory addresses as their values Normal variables contain a specific value (direct reference) num 7 Pointer contains an address of a variable that has a specific value (indirect reference) Indirection referencing a pointer value numptr num 7 4

Pointer Variable Definitions and Initialization Pointer definitions * is used with pointer variables int *numptr; Defines a pointer to an int (pointer of type int *) Multiple pointers require using a * before each variable definition int *numptr1, *numptr2; Can define pointers to any data type Initialize pointers to 0, NULL, or an address 0 or NULL points to nothing (NULL preferred) int *numptr = NULL; or int *numptr = 0; 5

Pointer Operators Symbol & is called address operator Returns address of operand int num = 7; int *numptr; numptr = &num; /* numptr gets address of num */ numptr numptr points to num num numptr 7 500000 600000 num 600000 7 Address of num is value of numptr 6

Pointer Operators Symbol * is called indirection/dereferencing operator Returns a synonym/alias of what its operand points to *numptr returns num (because numptr points to num) * can also be used for assignment Returns alias to an object *numptr = 10; /* changes num to 10 */ show pictures!! Dereferenced pointer (operand of *) must be an lvalue (no constants) * and & are inverses They cancel each other out 7

#include <stdio.h> int main() { int num; int *numptr; int num1=5; Sample program num = 7; printf("number = %d\n", num); numptr = &num; number = 7 numptr points to num whereby the value is = 7 Address of numptr : 1245060 Contents of numptr : 1245064 Address of num : 1245064 Dereferencing pointer, *numptr = 15 num = 20 *numptr = 20 *numptr + num1 = 25 printf("numptr points to num whereby the value is = %d\n",*numptr); printf("address of numptr : %d Contents of numptr : %d\n", &numptr, numptr); printf("address of num : %d\n\n", &num); } *numptr = 15; printf("dereferencing pointer, *numptr = %d\n", *numptr); num = num + num1; printf( num = %d\n, num); printf("*numptr = %d\n", *numptr); printf("*numptr + num1 = %d\n", *numptr + num1); return 0; 8

Calling Functions by Reference Call by reference with pointer arguments Passes address of argument using & operator Allows you to change actual location in memory Arrays are not passed with & because the array name is already a pointer * operator Used as alias or nickname for variable inside of function void fun1 (int *number) { *number = 2 * (*number); } *number used as nickname for the variable passed 9

#include <stdio.h> #include <string.h> Remember..last time char read(); void find_count_vc(char, int*, int*); void print(int,int); int main() { char ch, choice; int count_v=0,count_c=0; do { ch = read(); find_count_vc(ch, &count_v, &count_c); printf("do you want to continue?"); scanf("%c", &choice); getchar(); }while((choice == 'y') (choice =='Y')); print(count_v,count_c); return 0; } char read() { char ch1; printf("enter character : "); scanf("%c", &ch1); getchar(); return(ch1); } void find_count_vc(char ch1, int *vowel, int *consonant) { switch(ch1) } { case 'A': case 'a': case 'E': case 'e': case 'I': case 'i': case 'O': case 'o': case 'U': } Enter character : f Do you want to continue?y Enter character : I Do you want to continue?y Enter character : k Do you want to continue?n Number of vowel : 1 Number of consonant : 2 Functions that return more than one value i.e. arguments are passed by ref case 'u': *vowel = *vowel +1;break; default: *consonant = *consonant + 1; void print(int vowel, int consonant) { printf("number of vowel : %d\n", vowel); printf("number of consonant : %d\n", consonant); } 10

Pointer Expressions and Pointer Arithmetic Arithmetic operations can be performed on pointers Increment/decrement pointer (++ or --) Add an integer to a pointer (+ or +=, - or -=) Pointers may be subtracted from each other Operations meaningless unless performed on an array 11

Pointer Expressions and Pointer Arithmetic 5 element int array on machine with 4 byte ints vptr points to first element v[ 0 ] at location 3000 (vptr = 3000) vptr += 2; sets vptr to 3008 vptr points to v[ 2 ] (incremented by 2), but the machine has 4 byte ints, so it points to address 3008 location 3000 3004 3008 3012 3016 v[0] v[1] v[2] v[3] v[4] pointer variable vptr 12

Pointer Expressions and Pointer Arithmetic Subtracting pointers Returns number of elements from one to the other. If vptr2 = &v[ 2 ]; vptr = &v[ 0 ]; vptr2 - vptr would produce 2 Pointer comparison ( <, ==, > ) See which pointer points to the higher numbered array element Also, see if a pointer points to 0 13

Example of Pointer Operations #include <stdio.h> int main() {int *vptr; int *vptr2; int v[5] = {10,20,30,40,50}; int temp; int *p, *q; vptr= v; printf("address of vptr : %d Contents of vptr : %d\n", &vptr, vptr); printf("address of v[0] : %d\n", &v); vptr +=2; printf("address of vptr + 2: %d\n", vptr); vptr +=2; printf("address of vptr + 4: %d\n", vptr); Address of vptr : 1245064 Contents of vptr : 1245020 Address of v[0] : 1245020 Address of vptr + 2: 1245028 Address of vptr + 4: 1245036 Contents of temp : 2 Contents of p : 2147323904 q: 2147323904 vptr2=&v[2]; vptr=&v[0]; temp=vptr2-vptr; printf("contents of temp : %d\n", temp); p=q; printf("contents of p : %d q: %d\n", p,q); return 0;} 14

The Relationship between Pointers and Arrays Arrays and pointers are closely related Array name like a constant pointer Pointers can do array subscripting operations Define an array b[5] and a pointer bptr To set them equal to one another use: bptr = b; The array name (b) is actually the address of first element of the array b[5] bptr = &b[0]; Explicitly assigns bptr to the address of first element of b 15

The Relationship between Pointers and Arrays Element b[3] Can be accessed by *(bptr + 3) where * is the offset. Called pointer/offset notation Can be accessed by bptr[3] Called pointer/subscript notation bptr[3] same as b[3] Can be accessed by performing pointer arithmetic on the array itself *(b + 3) 16

Address of bptr : 1245064 Contents of bptr : 1245016 Address of b : 1245016 Contents of b[0]:10 10 10 bptr points to b[0] = 10 Example I am accessing element b[3]!! Let see how many ways I can do it b[3] = 40 *(bptr + 3) = 40 *(b + 3) = 40 bptr[3] = 40 #include <stdio.h> int main() { int *bptr ;int i; int b[10]={10,20,30,40,50}; bptr = b; b[0] = 10 b[1] = 20 b[2] = 30 b[3] = 40 b[4] = 50 b[5] = 0 b[6] = 0 b[7] = 0 b[8] = 0 b[9] = 0 printf("address of bptr : %d Contents of bptr : %d\n", &bptr, bptr); printf("address of b : %d Contents of b[0]:%d %d %d\n", &b, b[0], *bptr, *b); printf("bptr points to b[0] = %d\n", *bptr); printf("\ni am accessing element b[3]!!\nlet see how many ways I can do it\n"); printf("b[3] = %d\n", b[3]); printf("*(bptr + 3) = %d\n", *(bptr + 3)); printf("*(b + 3) = %d\n", *(b + 3)); printf("bptr[3] = %d\n\n", bptr[3]); for(i=0;i<10;i++) printf("b[%d] = %d\n", i, *(bptr+i)); return 0; } 17

Arrays of Pointers Arrays can contain pointers For example: an array of strings char *suit[4] = { Hearts, Diamonds, Clubs, Spades }; Strings are pointers to the first character char * each element of suit is a pointer to a char The strings are not actually stored in the array suit, only pointers to the strings are stored 18

Arrays of Pointers suit[0] H e a r t s \0 suit[1] suit[2] suit[3] D i a m o n d s \0 C l u b s \0 S p a d e s \0 suit array has a fixed size, but strings can be of any size 19

Example #include <stdio.h> #define N 5 int main() { char *studentname[n]; int i; for(i=0;i<5;i++) { printf("enter student[%d] name : ", i); scanf("%s", studentname + i); printf("you just entered :\n%s\n", studentname + i); } return 0; } Enter student[0] name : ali You just entered : ali Enter student[1] name : abu You just entered : abu Enter student[2] name : cheah You just entered : cheah Enter student[3] name : dali You just entered : dali Enter student[4] name : gheeta You just entered : gheeta 20