Pointers.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

Pointers in C Rohit Khokher
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program execution.
C Arrays and Pointers In Java, pointers are easy to deal with –In fact, there is little that can go wrong in Java since pointer access is done for you.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointers *, &, array similarities, functions, sizeof.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Lecture 10: 2/17/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CSC 215 Pointers and Arrays. Pointers C provides two unary operators, & and *, for manipulating data using pointers The operator &, when applied to a.
Pointers and Dynamic Memory Allocation
Dynamic Allocation in C
Pointers to pointers & multi-dimensional arrays
Object Lifetime and Pointers
Dynamic Storage Allocation
Computer Organization and Design Pointers, Arrays and Strings in C
Motivation and Overview
Pointers and Memory Overview
CSC113: Computer Programming (Theory = 03, Lab = 01)
Pointers Revisited What is variable address, name, value?
Arrays and Pointers CSE 2031 Fall September 2018.
Programming Languages and Paradigms
Lecture 6 C++ Programming
Pointers and References
Andy Wang Object Oriented Programming in C++ COP 3330
Pointers and References
Dynamic Memory Allocation
CSC215 Lecture Pointers and Arrays.
Object Oriented Programming COP3330 / CGS5409
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Arrays and Pointers Reference: Chapter , 4.11 CMSC 202.
Outline Defining and using Pointers Operations on pointers
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Pointers.
Chapter 16 Pointers and Arrays
Homework Starting K&R Chapter 5 Good tutorial on pointers
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Overloading functions
C++ Pointers and Strings
What have we learned about when we learned about function parameters?
Pointer Variables A pointer is a variable that contains a memory address The address is commonly the location of another variable in memory This pointer.
Homework Continue with K&R Chapter 5 Skipping sections for now
Chapter 9: Pointers and String
Pointers and dynamic objects
Arrays and Pointers (part 2)
Arrays and Pointers (part 2)
Pointers and References
C++ Pointers and Strings
Pointers, Dynamic Data, and Reference Types
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Pointers

Pointers What is pointer? A variable (2 or 4 bytes long) that can hold an Address Why pointers? Sometimes the only way to express a computation Usually lead to compact and efficient code Related operators: - * : can be used in two ways In declaration : read as pointer, e.g., int *p; In accessing : read as content of, e.g., x = *p; - & : returns LValue (address) of a variable Read as address of

Pointer Examples int x = 70, y = 80, z[4] = {10, 20, 30, 40 }; int *ip; // int pointer ip ip = &x; // ip is assigned to address of x *ip = 200; // content of ip is assigned to 200 y = *ip; // y is assigned to content of ip ip = &z[2]; *ip = *ip + 20; // same as *ip += 20; y = *ip+1; 70 ???? 80 10 20 30 40 x : 4892 200 4892 y : 4894 51 200 Z, Z[0] : 4896 Z[1] : 4898 Z[2] : 4900 50 4900 Z[3] : 4902 ip : 4904

Pointer Examples int x = 100; int *p1 = &x; cout << "&x == " << &x << " x == " << x << endl << "p1 == " << p1 << " *p1 == " << *p1 << endl; *p1 += 20; Output &x == 0x7fff7e60f41c x == 100 p1 == 0x7fff7e60f41c *p1 == 100 &x == 0x7fff7e60f41c x == 120 p1 == 0x7fff7e60f41c *p1 == 120

Pointers in Function arguments Arguments are passed by value, thus only a copy is passed. void swap_wrong(int x, int y) { int temp; temp = x; x = y; y = temp; } in swap_wrong in swap x: 10 4397 px: void swap(int *px, int *py) { int temp; temp = *px; *px = *py; *py = temp; } y: 20 9643 py: temp: temp: in caller: int a = 10, b = 20; swap_wrong(a, b); cout << a << b; swap(&a, &b); a:4397 10 b:9643 20

Referencing & Dereferencing pointer & * [] variable Referencing ( & ): create reference (pointer) to memory location Dereferencing (*, [ ] ): get the content of memory location Declaration Reference/Pointer/ Address/LValue Dereference/Variable/ Content/RValue int x; &x x int z[10], i; z z+i &z[i] z[0] *(z+i) z[i] int *ptr, i; ptr ptr+i &ptr[i] *ptr or ptr[0] *(ptr+i) ptr[i] Note: x = 10;  *(&x) = 10;

Pointer Operations The valid pointer operations are: Adding or subtracting a pointer and an integer (p  i) Assignment of pointers of the same type (p = q) Subtracting or comparing two pointers in same array (p - q) Assigning or comparing to zero. (p = 0) All other pointer arithmetic are illegal.

1– Addition/Subtraction with int Used for pointing to different elements in an array int a[6], *pa, x, i; pa = &a[2]; // same as pa = a + 2; *pa  pa[0]  a[2] *(pa-i)  pa[-i]  a[2-i] *(pa+i)  pa[i]  a[2+i] pa-2 pa-1 pa: pa+1 pa+2 pa+3 a: a[0] a[1] a[2] a[3] a[4] a[5] pointer  int  pointer

Addition/Subtraction with int Size of the pointed data-type is automatically taken care of. If address of a pointer (say ptr) is A then address of ptr+i is A+i*sizeof(data-type of ptr) long *lp; int *ip; char *cp; 7832 12 lp7832 *lp= 78563412 7832 12 7833 34 ip7832 *ip=3412 7833 34 7834 56 7832 12 7834 56 7835 78 cp7832 *cp=12 ip+17834 ip[1]=4456 7833 34 7835 44 7836 78 lp+17836 lp[1]= 12345678 7834 56 7836 33 ip+27836 ip[2]=5633 7837 56 cp+27834 cp[2]=56 7835 44 7837 56 7838 34 7839 12

Assignment of Pointers Pointers of same types can be assigned. float x = 10.5, *p = &x, *q = p; Pointer to void is used to hold any type of pointer int *ip; void *vp; vp = ip; // type casting is not essential Cannot be de-referenced without type casting. int x = *vp; // is illegal type casting is a must int y = *((int *)vp); // is ok

Comparing/Subtraction to Pointer The resulting type of subtracting two pointers is integer. Comparison Vs. Subtraction a < b  a – b < 0 a == b  a – b == 0 a > b  a – b > 0 Compared/Subtracted pointers should point in same array. Example: /* strlen: return length of string s*/ int strlen(char *s) { char *p = s; while (*p != ‘\0’) p++; return p – s; } pointer - pointer  int

Comparing/Assigning to Zero Zero is the only integer that can be assigned to a pointer Zero is the only integer that a pointer can be compared to. Use this to initialize a pointer and to check validity char *m = 0; ... if (m != 0) { ... safe to use the pointer ... } NULL can be used instead of 0

Pointer Vs Array pmessage is pointer and requires 2/4 bytes for itself amessage: now is the time\0 char amessage[] = “now is the time”; // an array char *pmessage = “now is the time”; // a pointer pmessage: now is the time\0 pmessage is pointer and requires 2/4 bytes for itself pmessage++ is possible pmessage=somepointer is legal amessage is a name for the starting address of the array amessage++ is illegal amessage=somepointer is illegal

strcpy example /* strcpy: copy t to s */ void strcpy(char *s, char *t) { int i; i = 0; while ((s[i] = t[i])!=‘\0’) i++; } Note: if you just write s=t then only the pointer will be copied, not the characters /* strcpy: copy t to s */ void strcpy(char *s, char *t) { while ((*s = *t)!=‘\0’) { s++; t++; } /* strcpy: copy t to s */ void strcpy(char *s, char *t) { while ((*s++ = *t++)!=‘\0’) ; }

Pointer Vs Array In function argument array and pointer are same. i.e., following declaration/definition of function are equivalent int strlen(char *str) int strlen(char str[ ]) Arguments are passed by value, thus only a copy is passed. /* strcpy: copy t to s */ void strcpy(char *s, char *t) { while (*s++ = *t++) //DO NOTHING; } ……… char p[25]; char *q = “Hello world”; strcpy(p, q); 4397 s: 9643 t: 4397 p: q: Hello world\0 9643 What is the effect of writing s=t?

strcmp example // strcmp: return <0 if s<t, 0 if s==t, >0 if s>t int strcmp(char *s, char *t) { int i; for (i = 0; s[i] == t[i]; i++) if (s[i] == ‘\0’) return 0; return s[i] – t[i]; } // strcmp: return <0 if s<t, 0 if s==t, >0 if s>t int strcmp(char *s, char *t) { for ( ; *s == *t; s++, t++) if (*s == ‘\0’) return 0; return *s – *t; }

Dynamic Memory Management Program image in RAM Can be accessed via getenv function Environment variables char *gvar = “some string”; int max_size = 200; int myfunc(int x) { int y = 20; x = x + y; return x * y; } int main(void) { int *px = new int; cin >> x; cout << myfunc(x); delete px; Static Data Stack Heap Program code

Dynamic Memory Allocation // Allocating array int *parr = new int[10]; delete [] parr; // Allocating data for reference class Foo { …………}; Foo *p = new Foo(); p->c1 = ′X′; delete p; // explicit free Foo &r = *new Foo(); r.c1 = ′X′; delete &r; // explicit free

Pointer Anomalies Uninitialized variable : Before storage can be used, it must be allocated. Foo *p; // forget to initialize pointer with “new” p->c1 = ′R′;// places ′R′ at random location in memory After storage is no longer needed it must be explicitly deleted otherwise memory leak results. Foo *p = new Foo; p = new Foo; // forgot to free previous storage After storage is deleted, it must not be used: delete p; p->c1 = ′R′; // result of dereference is undefined p is called a dangling pointer.

Pointers Vs. Multi-dim Arrays int m[10][20] m is a 2D array: 200 int sized locations have been set aside m[row][col] is calculated as 20row+col int *pm[10] pm is a 1D array of pointers to int. Only 10 pointers are allocated pm[i] must be initialized/allocated with code (malloc) or static initialized (like name array) int **ppm c is a pointer of pointers to int. Only 1 pointer is allocated c must be initialized/allocated with code (malloc) c[i] must be initialized/allocated with code (or static initialized (like name array) Examples in next slide m 20 … 10 … … … … pm 10 ppm

Pointers Vs. Multi-dim Arrays int m[3][4]; for (int r = 0; r < 3; r++) for (int c = 0; c < 4; c++) m[r][c] = (r+1)*10 + c; int *pm[3]; for (int r = 0; r < 3; r++) { pm[r] = new int[4]; pm[r][c] = (r+1)*10 + c; } int **ppm = new int *[3]; ppm[r] = new int[4]; ppm[r][c] = (r+1)*10 + c; 10 11 12 13 20 21 22 23 30 31 32 33

Multi-dimensional Array : Formal Parameters In function parameter only the left most dimension is unnecessary. Thus all the following are equivalent: void func(int daytab[2][13]) { … } void func(int daytab[][13]) { … } void func(int (*daytab)[13]) { … } The brackets in last statement is necessary since [ ] have higher precedence than *. int (*daytab)[13] : a pointer to an array of 13 elements int *daytab[13] : an array of 13 pointers to integers. 12 daytab daytab[0] [1] [12]

Complicated Declarations Read C declarations using a counter-clock wise spiral Do not cross a bracket (**a[]) unless all the tokens within the bracket are finished int *f() int * f () f is a function returning int * int (*f)() int ( * fp ) () fp is a pointer to function returning int

Complicated Declarations char (*(*x())[5])() char ( * ( * x () ) [5] ) () x is a function returning pointer to array[5] of pointer to function returning char char (*(*x[3])())[5] x is a array[3] of pointer to function returning pointer to array[5] of char

Command-line Arguments main is called with two arguments : int argc: is the number of command-line arguments char **argv: pointer to array of strings (i.e., char *) int main(int argc, char **argv) echo.c invoked with: echo hello world argc is 3 and argv is  argv [2] [0] echo\0 hello\0 world\0 [1] [3] #include <iostream> int main(int argc, char **argv) { for (int i = 1; i < argc; i++) std::cout << argv[i] << " "; std::cout << endl; }

Command-line Arguments /* Processing command-line options: like –abc –x –v */ int main(int argc, char **argv) { while (--argc > 0 && (*++argv)[0] == ‘-’) { // each option group while (c = *++argv[0]) { // for each option in the goup // process the option } find.exe\0 argv (*++argv)[0] ++argv (*++argv) - x f r \0 -m\0

Command-line Arguments /* Processing command-line options: like –abc –x –v */ int main(int argc, char **argv) { while (--argc > 0 && (*++argv)[0] == ‘-’) { // each option group while (c = *++argv[0]) { // for each option in the group // process the option } find.exe\0 argv ++argv[0] argv[0] - x f r \0 *++argv[0] -m\0

Pointers to Functions In C/C++, a function itself is not a variable But pointer to function can be created int (*comp)(void *, void *); comp is a pointer to function that returns int and takes two void * type arguments BEWARE: int *comp(void *, void *) means that comp is a function that that returns int * and takes two void * type arguments int result = (*comp)(&x, &y) invokes comp with parameters x and y

Pointer to Function : Example

Be Careful with * and ++/-- * and ++ / -- are executed from right to left char *p = “XAD”; char *q = p; char c; Statement c p q Comment c = ++*q; ‘Y’ “YAD” p Increment content of q and return new value. (*q)++; c = *q; c = *++q; ‘A’ “XAD” p+1 Increment q and fetch content. q++; c = *q; c = *q++; ‘X’ “XAD” p+1 fetch content of q and then increment q. i.e., c = *q; q++; c = (*q)++; ‘X’ “YAD” p Return content of q and then increment content of q. i.e. c = *q; (*q)++; The above is also true for the – – operator.

Coercion: Storage of Values in Memory Same memory location can be interpreted in different ways: long int Intrepreted as 1 long int 41 43 45 47 0x41434547 short int 7832 47 Intrepreted as 2 short int 45 47 0x4547 7833 45 41 43 0x4143 7834 43 7835 41 char 47 ‘G’ Intrepreted as 4 char 4-bytes in RAM 45 ‘E’ Note: All numbers in this slide are in hexadecimal system. 43 ‘C’ Higher bits stored in higher address 41 ‘A’

Coercion: Assignment of Pointers Cast and then assign int i = 0x4145, *ip = &i; char *cp = (char *)ip; cout << *cp << endl << cp[1] << endl << showbase << hex << int (*cp) << endl << int (cp[1]) << endl << *ip << endl ; cp:8996 *cp: E 78 38 *(cp+1): A 45 i:7838 41 7839 RAM bytes hi-8bits[7839] lo-8bits[7838] Logical View 78 38 *ip: 41 45 ip:8976

Coercion: Assignment of Pointers Cast and then assign long int l = 0x41434547, *lp = &l; int *ip = (int *)lp; // same as int *ip = (int *)&l; char *cp = (char *)lp; // same as char *ip = (char *)&l; 7833 7834 7835 47 l:7832 45 RAM bytes 43 41 lp:8974 78 32 Note: lp, ip and cp are all of size 2 bytes though they are pointing to data of different sizes, 4, 2 and 1 bytes, respectively. ip:8976 78 32 cp:8978 78 32

Coercion: Assignment of Pointers Cast and then assign long int l = 0x41434547, *lp = &l; int *ip = (int *)lp; char *cp = (char *)lp; cout << *cp << *(cp+1) << *(cp+2) << *(cp+3) << *ip << *(ip+1) << *lp; *cp=‘G’ 47 7832 45 RAM bytes 43 41 7833 7834 7835 *(cp+1) =‘E’ *(cp+2) =‘C’ *(cp+3) =‘A’ *ip 0x4547 *(ip+1) 0x4143 47 7832 45 7833 RAM bytes 43 41 7834 7835 47 7832 45 7833 RAM bytes 43 41 7834 7835 *lp 0x41434547