Pointers.

Slides:



Advertisements
Similar presentations
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
Advertisements

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.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
Dynamic Objects. COMP104 Dynamic Objects / Slide 2 Memory Management * Static Memory Allocation n Memory is allocated at compiling time * Dynamic Memory.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Dynamic Objects. COMP104 Lecture 31 / Slide 2 Static verses Dynamic Objects * Static object n Memory is acquired automatically  int A[10]; n Memory is.
Dynamic Objects. COMP104 Dynamic Objects / Slide 2 Memory Management * Static Memory Allocation n Memory is allocated at compilation time * Dynamic Memory.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Pointers and Dynamic Objects Mechanisms for developing flexible list representations.
Pointers and dynamic objects COMP171 Fall Pointers and dynamic objects/ Slide 2 Topics * Pointers n Memory addresses n Declaration n Dereferencing.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Pointers. COMP104 Pointers / Slide 2 Pointers * A pointer is a variable used for storing the address of a memory cell. * We can use the pointer to reference.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
Programming Pointers. COMP104 Lecture 32 / Slide 2 Pointers l Pointers are objects whose values are the locations of other objects l Pointers are memory.
HKUST Summer Programming Course 2008
Pointers. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program execution.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Chapter 5 – Dynamic Data Structure Par1: Abstract Data Type DATA STRUCTURES & ALGORITHMS Teacher: Nguyen Do Thai Nguyen
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Pointers and Dynamic Objects Mechanisms for developing flexible list representations JPC and JWD © 2002 McGraw-Hill, Inc.
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.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
Pointers and Dynamic Memory Allocation. Declaring a pointer.
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.
Review 1 List Data Structure List operations List Implementation Array Linked List.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
Pointers CSC1201: Programming Language 2. Topics Pointers ▫Memory addresses ▫Declaration ▫Dereferencing a pointer ▫Pointers to pointer.
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
Pointers and Dynamic Memory Allocation
Dynamic Storage Allocation
Pointers and Dynamic Arrays
Standard Version of Starting Out with C++, 4th Edition
Motivation and Overview
Pointers Revisited What is variable address, name, value?
Pointers.
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
CSCE 210 Data Structures and Algorithms
Pointers and References
Dynamic Memory Allocation
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Pointers and dynamic objects
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes
Pointers, Dynamic Data, and Reference Types
Programming II Pointers and arrays by aalosaimi.
Objectives You should be able to describe: Addresses and Pointers
Dynamic Objects.
Pointers and dynamic objects
Standard Version of Starting Out with C++, 4th Edition
Pointers and dynamic objects
Pointers and References
Pointers, Dynamic Data, and Reference Types
Dynamic Objects.
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Pointers

Why pointers? - low-level, but efficient manipulation of memory - dynamic objects Objects whose memory is allocated during program execution. (Dynamic objects can survive after the function ends in which they were allocated). Dynamic objects allow flexible-sized arrays and lists

Pointers A pointer is a variable used for storing the address of a memory cell. We can use the pointer to reference this memory cell, so to ‘manipulate’ it! Object whose value represents the location (memory address) of another object Memory address: 1020 1024 10032 … … 100 … 1024 … int a; int* p; Integer a Pointer p

Getting an address: address operator & int a=100; “&a”  “the address of a” Memory address: 1020 1024 … … 100 … … … a int a = 100; cout << a;  100 Cout << &a;  1024

Define a pointer type variable: T* Each type of object (variable) has a pointer type, therefore a pointer variable of that type. TypeName* variablename; int* p; equivalent TypeName *variablename; int *p; Examples of (uninitialized) pointers int* ip; char* s; int *ip; // ip is a pointer to an int char *s; // s is a pointer to a char

Store the address in a pointer variable Memory address: 1020 1024 10032 … 88 100 … 1024 … a p int a = 100; int* p = &a; cout << a << " " << &a <<endl; cout << p << " " << &p <<endl; Result is: 100 1024 1024 10032 The value of pointer p is the address of variable a A pointer is also a variable, so it has its own memory address p is pointing to a

Dereferencing Operator * We can access to the value stored in the variable pointed to by preceding the pointer with the “star” operator (*), Memory address: 1020 1024 10032 … 88 100 … 1024 … a p int a = 100; int* p = &a; cout << a << endl; cout << &a << endl; cout << p << " " << *p << endl; cout << &p << endl; *p gives 100

An asterisk (‘*’) has two usages In a definition, an asterisk indicates that the object is a pointer. char* s; // s is of type pointer to char (char *s; is possible) In expressions, an asterisk before a pointer indicates the object the pointer pointed to, called dereferencing int i = 1, j; int* ptr; // ptr is an int pointer ptr = &i; // ptr points to i j = *ptr + 1; // j is assigned 2 cout << *ptr << j << endl; // display "12"

Summary on two operators * and & * has two usages: - pointer - dereferencing & has two usages: - getting address - reference (‘call by ref’, see later)

Null Address 0 is a pointer constant that represents the empty or null address Indicates that pointer is not pointing to storage of a valid object Cannot dereference a pointer whose value is null int* ptr; ptr = 0; cout << *ptr << endl; // invalid, ptr // does not point to // a valid int

Example #include <iostream> using namespace std; int main (){ int value1 = 5, value2 = 15; int* p1; int* p2; p1 = &value1; // p1 = address of value1 p2 = &value2; // p2 = address of value2 *p1 = 10; // value pointed to by p1=10 *p2 = *p1; // value pointed to by p2= value // pointed to by p1 p1 = p2; // p1 = p2 (pointer value copied) *p1 = 20; // value pointed to by p1 = 20 cout << "value1==" << value1 << "/ value2==" << value2; return 0; } Result: Value1 is 10 Value2 is 20

Another Pointer Example int a = 3; char s = ‘z’; double d = 1.03; int* pa = &a; char* ps = &s; double* pd = &d; cout << sizeof(pa) << sizeof(*pa) << sizeof(&pa) << endl; cout << sizeof(ps) << sizeof(*ps) << sizeof(&ps) << endl; cout << sizeof(pd) << sizeof(*pd) << sizeof(&pd) << endl;

Writing pointer type properly in C++ … Recommended: int* a; int* b; ? int *a, *b; a, b are both integer pointers int* a, b; a is integer pointer, b is just integer! typedef int MyInt; MyInt k; int k; typedef int* IntPt; IntPt a, b;

Traditional Pointer Usage void swap(char* ptr1, char* ptr2){ char temp = *ptr1; *ptr1 = *ptr2; *ptr2 = temp; } int main() { char a = 'y'; char b = 'n'; swap(&a, &b); cout << a << b << endl; return 0; Use pass-by-value of pointers to ‘change’ variable values C language does not have ‘call by reference’, only ‘call by value’!

Reference: T& void f(int& b) {}; int main() { int a; int& b a; f(a); b is an alternative name for a

Pass by reference (better than ‘pointers’) void swap(char& y, char& z) { char temp = y; y = z; z = temp; } int main() { char a = 'y'; char b = 'n'; swap(a, b); cout << a << b << endl; return 0; y, z are ‘references’, only names, not like ptr1, ptr2 that are variables

Pointer to ‘Struct’ struct Date {…}; Date d={1,10,2009}; Date* pd = &d; (*pd).day=2; (*pd).month=11; Or pd->day=2; pd->month=11;

Pointers and arrays

Arrays are pointers! The name of an array points only to the first element not the whole array. 1000 1004 1008 1012 1016

Array name is a pointer constant #include <iostream> Using namespace std; void main (){ // Demonstrate array name is a pointer constant int a[5]; cout << "Address of a[0]: " << &a[0] << endl << "Name as pointer: " << a << endl; } /* result: Address of a[0]: 0x0065FDE4 Name as pointer: 0x0065FDE4 */ &a = &a[0] = a, But its semantics is not that clear An array name is converted to a pointer to the first element most of the time. The official standard terminology is that an array name is converted to a pointer to the first element when used in a value context as opposed to an object context. A value context is when you're retrieving and subsequently using the value of an object, such as the right hand side of x = y; . An object context is when you're modifying or querying the object itself, not the value it contains. The left hand side of x = y; is one example.

Dereference of an array name #include <iostream> Using namespace std; void main(){ int a[5] = {2,4,6,8,22}; cout << *a << " " << a[0] << " " << *(&a[0]); ..." } //main a[0] 2 Result is: 2 a[1] 4 a[2] 6 a[3] 8 a[4] 22 This element is called a[0] or *a

Array name as pointer To access an array, any pointer to the first element can be used instead of the name of the array. We could replace *p by *a #include <iostream> Using namespace std; void main(){ int a[5] = {2,4,6,8,22}; int* p = a; int i = 0; cout << a[i] << " " << *p; ... } 2 4 8 6 22 a[4] a[0] a[2] a[1] a[3] a p 2 2 a

Multiple Array Pointers Both a and p are pointers to the same array. #include <iostream> Using namespace std; void main(){ int a[5] = {2,4,6,8,22}; int* p = &a[1]; cout << a[0] << " " << p[-1]; cout << a[1] << " " << p[0]; ... } A[0] 2 2 4 4 a[0] 2 p a[1] 4 a[2] 6 P[0] a[3] 8 a[4] 22

Pointer Arithmetic Given a pointer p, p+n refers to the element that is offset from p by n positions. 2 4 8 6 22 p - 1 a p a + 1 p + 1 a + 2 p + 2 a + 3 a + 4 p + 3

Dereferencing Array Pointers a[0] or *(a + 0) 2 4 8 6 22 a a + 2 a + 4 a + 3 a + 1 a[1] or *(a + 1) a[2] or *(a + 2) a[3] or *(a + 3) a[4] or *(a + 4) *(a+n) is identical to a[n]

Summary * two usages: - pointer type definition: int a; int* p; - dereferencing: *p is an integer variable if p = &a; & two usages: - getting address: p = &a; - reference: int& b a; b is an alternative name for a First application in passing parameters (‘swap’ example) int a=10; int b=100; int* p; int* q; p=&a; q=&b; p = q; *p = *q; ? ?

Two ways of manipulating an array a[n]: like a vector, an array a+n *(a+n): like a ‘sequence’ or a ‘list’ ‘a’ points to the first element

Dynamic Objects

Memory Management Static Memory Allocation Dynamic Memory Memory is allocated at compiling time Dynamic Memory Memory is allocated at running time { int a[200]; … } { int n; cin >> n; a[n]??? }

Static vs. Dynamic Objects Static object Memory is acquired automatically Memory is returned automatically when object goes out of scope Dynamic object Memory is acquired by program with an allocation request new operation Dynamic objects can exist beyond the function in which they were allocated Object memory is returned by a deallocation request delete operation

Creating a variable (object): new T Syntax ptr = new SomeType; where ptr is a pointer of type SomeType Example int* p = new int; p Uninitialized int variable ‘new’ does two things: Create a variable of given type Point the pointer p to the variable

Destructing a variable (object): delete p Syntax delete p; storage pointed to by p is returned to free store and p is now undefined Example int* p = new int; *p = 10; delete p; ‘delete’ does two things: Return the pointed object to the system Point the pointer p to NULL p 10

Dynamic Arrays (a collection of variables) p = new T[size]; delete[] p; Syntax for allocation: p = new SomeType[Expression]; Where p is a pointer of type SomeType Expression is the number of objects to be constructed -- we are making an array Syntax for de-allocation: delete[] p; Because of the flexible pointer syntax, p can be considered to be an array C++ keeps track of the size of the ‘dynamically allocated’ array from the heap, This size is kept by the system, that’s why ‘delete[]’ knows the size.

Example Dynamic Memory Allocation p p p Request for “unnamed” memory from the Operating System int* p, n=10; p = new int; p = new int[100]; p p p = new int[n]; p

Freeing (or deleting) Memory

Allocation Example Need an array of unknown size int grades[n]; main() { int n; cout << “How many students? “; cin >> n; int* grades = new int[n]; for(int i=0; i < n; i++){ int mark; cout << “Input Grade for Student” << (i+1) << “ ? :”; cin >> mark; grades[i] = mark; } . . . printMean( grades, n ); // call a function with dynamic array

Dangling Pointer Problem int* A = new int[5]; for(int i=0; i<5; i++) A[i] = i; int* B = A; delete[] A; B[0] = 1; // illegal!

Memory Leak Problem int* A = new int[5]; for(int i=0; i<5; i++) A[i] = i; A = new int[5]; A 1 2 2 3 4

Summary Static variables (objects) Dynamic variables (objects) A (direct) named memory location A static part (pointer) + (indirect) nameless memory location (dynamic part) int a; a = 20; int* pa; pa = new int; *pa = 20; 20 20 a pa static dynamic static

int* p = new int; int* p = new int[100]; *p = 10; Dynamic array Simple dynamic variable int* p = new int; *p = 10; delete p; int* p = new int[100]; for (i=1;i<100,i++) p[i] = 10; delete[] p; 10 10 p 10 p 10 ‘delete’ two actions: Return the object pointed to Point the pointer p to NULL ‘delete p’ is not sufficient for an array!!!

Good practice Logically, Initialize a pointer with NULL Always check a pointer before usage if (p != NULL) *p

n=100; int* p = new int[n]; { int n; cin >> n; N=150; a[n]??? Bad examples n=100; int* p = new int[n]; N=150; P[130]??? { int n; cin >> n; a[n]??? } It’s possible, but not standard, Do: int* a = new int[n]; No! the array stays with the size 100.

More pointers

Pointers to pointers

Pointer to pointer: T** int a; int* p; int** q; a = 58; p = &a; q = &p; a p q 58 a, *p, and **q are the same object whose value is 58! But q = &a is illegal!

Pointer to pointers and 2D arrays

Pointer of pointers & 2D Arrays What is **table ? table[i][j] table table[0] or *( table + 0 ) table + 1 table[1] or *( table + 1 ) table + 2 table[2] or *( table + 2 ) int table[3][4]; for(int i=0; i<3; i++){ for(int j=0; j<4; j++) cout << *(*(table+i) +j); cout << endl; }

table and table[0] are of the same address int table[2][2] = {{0,1}, {2,3}}; cout << table << endl; cout << *table << endl; //same as above cout << table[0] << endl; // same as above cout << *table[0] << endl; cout << table[0][0] << endl; // same as above cout << **table << end; // same as above 0xffbff938

Array of Pointers & Pointer to Array b c A pointer to an array An array of Pointers int a = 1, b = 2, c = 3; int* p[5]; p[0] = &a; p[1] = &b; p[2] = &c; int list[5] = {9, 8, 7, 6, 5}; int* p; p = list;//points to 1st entry p = &list[0];//points to 1st entry p = &list[1];//points to 2nd entry p = list + 1; //points to 2nd entry

A Dynamic Table table table[0] table[1] table[2] table[3] table[4] A dynamic table is an array of pointers to save space when not all rows of the array are full. table[0] table[1] table[2] table[3] table[4] table[5] table int** table; table = new int*[6]; table[0] = new int[4]; table[1] = new int[7]; table[2] = new int[1]; table[3] = new int[3]; table[4] = new int[2]; table[5] = NULL;

32 18 24 12 42 14 19 16 11 13 22 table table[0] table[1] table[2] *(*(table+i)+j) is table[i][j] table[0][0] = 32; table[0][1] = 18; …

Create a matrix of any dimensions, m by n: Ideas: Put it into a function: int main() { int m, n; cin >> m >> n >> endl; int** matrix; matrix = imatrix(m,n); … } int** imatrix(int m, int n) { int** mat; mat = new int*[m]; for (int i=0;i<n;i++) mat[i] = new int[n]; return mat; int m, n; cin >> m >> n >> endl; int** mat; mat = new int*[m]; for (int i=0;i<m;i++) mat[i] = new int[n];

Dynamic matrix deallocation for(int i=0; i<6; i++) delete[] mat[i]; delete[] mat; void deleteImatrix(int** mat, int m, int n) { for(int i=0; i<m; i++) delete[] mat[i]; delete[] mat; } Each row must be deleted individually Be careful to delete each row before deleting the table pointer.

Examples: main() arguments int main()  int main(int argc, char* argv[]) E.g. a.out 20 30 int main(int argc, char* argv[]) { if (argc != 3) { troubles!!!} int rows = atoi(argv[1]); int col = atoi(argv[2]); } ‘argc’ is the actual number of arguments ‘argv’ is an array of char*, each pointing to a character

Constantness: object or pointer?

(const) object (*const) pointer ‘const’ only modifies a type const T* p  constant T, so constant object, const *p ‘const’ only modifies a type as it might be one of them: const T* p const T *p T *const p  constant pointer const T *const p  = constant pointer to constant object (both pointer AND object are constants!) No ‘const*’ operator.

Example: A constant object with ‘const’: const int* p; A constant pointer with ‘*const’: int *const p; A constant object AND pointer is: const int *const p; 57

‘const object’ and ‘constant pointer’ Pointer to const object: the content is const, pointer is free int x=10, y=20; const int* pc = &x; pc = &y // OK *pc = 5; // wrong! Const pointer: the pointer is const, content is free Int *const cp = &x; *cp = 5; // OK cp = &y; // wrong!  int const *pc

Because of ambiguous ‘const int** b’ and ‘const int **b’, so it is ‘const int’! int main(){ int** iptr; int i, j; iptr = new int*[10]; for( i = 0; i < 10; i++ ) iptr[i] = new int[10]; for( j = 0; i < 10; i++ ) iptr[i][j] = i*j; f1(iptr); f2(iptr); f3(iptr); } void f1(const int** bar){ bar[1][1] = 5; // wrong: change int bar[1] = new int[3]; // ok } void f2(int *const *bar){ bar[1][1] = 5; // ok bar[1] = new int[3]; // wrong: change int* bar = new int*[3]; // ok void f3(int **const bar) { bar[1][1] = 5; // ok bar[1]= new int[3]; // ok bar = new int*[3]; // wrong: change int** Bad: const int ** bar Bad: int * const * bar Writing properly matters!!! 59

More examples … 60 int main(){ int i = 3, j = 10; int* ip = &i; const int* ipc = ip; *ip = 5; // *ipc is now 5 ip = &j; int *const *ipp1 = &ip; // ok const int* const *ipp2 = &ip; // ok const int** ipp3 = &ipc; // ok ipp3 = &ip; // wrong: changing ipp3 // indirectly/inadvertently changes **ipp const int** ipp4 = &ip; // wrong: same reason as above, because if allowed ipp4 //could be changed later return 0; } 60