Computational Intelligence on Automation Lab @ NCTU Outlines

You should be able to review/understand: UEE1303(1070) S’12 . Fundamentals of ++ pointer –difference between C and C++ pointers Object-Oriented . References Programming in C++ –as a reference variables –pass to functions –return by functions Lecture 02: . Using references and pointer with constants Pointers, References, and . Dynamic memory allocation Dynamic Memory Allocation –dynamic arrays –pass/return array to/from function

LECTURE 02 UEE1303(1070) 2

Introduction C/C++ Pointer

. C pointers are very powerful . A pointer is a variable that is used to store a –but prone to error if not properly used memory address –including system crashes –can be a location of variable, pointer, function . C++ enhances C pointers and provides increased security because of its rigidity . Major benefits of using pointers in C/C++: –by providing a new kind of pointer –support dynamic memory allocation reference –provide the means by which functions can . References have advantages over regular modify their actual arguments pointers when passed to functions –support some types of data structures such as linked lists and binary trees. –improve the efficiency of some programs

LECTURE 02 UEE1303(1070) 3 LECTURE 02 UEE1303(1070) 4

1 Pointer Operators for Pointers

. A pointer variable is declared using . Indirection operator (*) precedes a pointer datatype *variable_name; and returns the value of a variable datatype * variable_name; –Address of the variable is stored in the datatype* variable_name; pointer . Data type that the pointer points can be any –dereferencing : access the value that the valid C/C++ type including void types and pointer points to user-defined types . Address-of operator (&) returns the memory int *ptr1; address of its operand double *ptr2; float x = 1.23, y; void *ptr3; //can point to a variable float *pt; //point to any float variable //of any datatype pt = &x; //place x’s address into pt AirTicket *ptr4; //user-defined datatype cout << *pt; //print x’s value 1.23

LECTURE 02 UEE1303(1070) 5 LECTURE 02 UEE1303(1070) 6

Pointer Expressions Point to Another Pointer

. Pointers can be used as operands in . When declaring a pointer that points to assignment, arithmetic (only + and -), and another pointer, two asterisks (**) must comparison expressions precede the pointer name . Example . Example 00005cfe 0000ab40 float f=13.3, *p1, *p2; 00003002 p2 = p1 = &f; //p1 and p2 point to f 00005cfe 0000ab40 0.99 p1--; //decrementing ptrl cout << pl; //pl is 992=1000-8 float** float* float p2 += 5; //add 5 and assign to p2 float a=0.99, *b, **c; cout << ptr2; //p2 is 1040=1000+5*8 if (p1==p2){ //compare two addresses by == b = &a; //pointer b points to variable cout << “Two addresses are the same” c = &b; //pointer c points to pointer << endl; cout << **c; //dereferencing pointer c } //two times to access var a LECTURE 02 UEE1303(1070) 7 LECTURE 02 UEE1303(1070) 8

2 Access Array by Pointer Differences between C and C++

. An array name . C++ is much more strict than C –the starting address of the array –when dealing with pointers –the address of the first element of the array –especially apparent for void pointers –can also be used as a pointer to the array  . A void pointer is a raw address faster than index –Compiler has no idea what type (can be . Example: int array[3] = {1, 2, 3}; any type) of object being pointed to array indexing pointer notation . Format: void *vaiable_name; array[0] *array void *p1; array[1] *(array + 1) int *p2, x = 3; array[2] *(array + 2) p1 = p2 = &x; //p1 and p2 both point to x //ERROR! p1 can’t be directly dereferenced.

LECTURE 02 UEE1303(1070) 9 int y = *p1; //int y = *(int *)p1; LECTURE 02 UEE1303(1070) 10

Function Pointers void Pointers

. A function block also occupies memory space // fun.cpp –placed at Code Section void fun1(void (*fp)(void *), void *q) { fp(q); –has its own address } . function pointer  a pointer to the function void fun2(void *r) { int a = * (int *) r; –Ex: int (*fp)(char a, int b); cout << a << endl; } –() has higher precedence than * . Ex: int fc1(char x, int y); //main() block in main.cpp int (*fp2)(char a, int b); int var = 22; int fn3(double x); void *p = &var; fp2 = fn1; //OK!! Same type fun1(fun2, p); fp2 = fn3; //Error fp2=fc1(‘x’, 5); //Error! . fp is a void pointer that points to a function

LECTURE 02 UEE1303(1070) 11 LECTURE 02 UEE1303(1070) 12

3 References References As Independent Variables

. C++ provides a new kind of variables called . Put & before the variable when declared references –The type of reference variable should be the –a reference is an implicit pointer that is same as the type of the variable it refers automatically dereferenced –reference variables have to be initialized –need not use * to get values when declared –also act as alternative names for variables . Format: datatype & ref_var = old_var; . A reference can be used in three ways: . Example: –created as an independent variable double num = 6.75; –passed to a function ... –returned by a function double & refnum = num; . Passing references between functions is a – refnum is initialized to num as its alias powerful, important use

LECTURE 02 UEE1303(1070) 13 LECTURE 02 UEE1303(1070) 14

Passing References To Function Example of Passing References

. C++ supports the three methods for passing //swap.cpp values to functions: void swap(int &x, int &y) { int temp = x; –pass by value x = y; –pass by address y = temp; –pass by reference } . Passing a reference to a function is like //main() in main.cpp passing the address of the variable to such int main() { int a(4), b(11); //a=4 and b=11 function, but with advantages: cout << a << “ ” << b << endl; –code is cleaner swap(a, b); –no copy of function arguments cout << a << “ ” << b << endl; return 0; –not remember to pass the address }

LECTURE 02 UEE1303(1070) 15 LECTURE 02 UEE1303(1070) 16

4 Constant References Returning Reference by Function

. Reference parameters preceded with const . A function may return a reference –can prevent a function from changing them –particularly important when overloading inadvertently some types of operators . Example: –Ex: inserter and extractor (in later lecture) –also permits the function to be called from void fun(const int &cref) { the left side of the assignment operator cout << cref/15; //no problem! int & fun(int * a, int i) { cref++; //error! cannot modify it if (i>0 && i<5) return a[i]; } else exit(0); } //iary: an integer array for (int idx=0; idx<5; idx++) fun(iary, idx) = idx*2; LECTURE 02 UEE1303(1070) 17 LECTURE 02 UEE1303(1070) 18

References/Pointers with Constants A Reference to a Constant

. If the const modifier is used onto references . A read-only alias and pointers, one of the following four types –cannot be used to change the value it can be created references –a reference to a constant . However, a variable that is referenced by this –a pointer to a constant reference can be changed . Example: –a constant pointer –a constant pointer to a constant int x = 8; const int & xref=x; //a ref to a const. x = 33; cout << xref ; xref = 15; //ERROR! cannot modify xref x = 50; //OK

LECTURE 02 UEE1303(1070) 19 LECTURE 02 UEE1303(1070) 20

5 A Pointer to a Constant A Constant Pointer

. A constant pointer is a kind of pointers that its int x = 4, y = 7; const int *pt = &x; //a pointer to a const. content is constant and cannot be changed cout << *pt; //print 4 on screen –cannot be changed to point to another pt = &y; variable cout << *pt; //print 7 on screen –but can change the value it points to *pt = 11; //ERROR! cannot modify . Example . The pointer pt to a constant used in this int var1 = 3, var2 = 5; example can store different addresses //a constant pointer to a declared variable int * const cpt = &varl; –can point to different variables, x or y *cpt = 8; //change the value cpt points to . However, cannot change the dereferenced cout << var1; //print 8 on screen value that pt points to //ERROR! a const. pointer cannot be changed cpt = &var2;

LECTURE 02 UEE1303(1070) 21 LECTURE 02 UEE1303(1070) 22

A Constant Pointer to a Constant Memory Allocation

. A constant pointer to a constant . Static memory allocation –cannot be used to change the constant –uses the explicit variable and fixed-size value to which it points. array declarations to allocate memory –can be changed to point to another –reserves an amount of memory allocated constant of the same type when a program is loaded into the memory . Example: –a program could fail when lacking enough const int vl = 11, v2 = 22; memory //a constant pointer to a constant –or reserve an excessive amount of memory const int *cptc = &v1; //v1 is constant so that other programs may not run *cptc = 33; //ERROR! cannot modify cout << *cptc; //print 11 on screen . What if the size can be known until the cptc = &v2; program is running? cout << *cptc; //print 22 on screen  dynamic memory allocation

LECTURE 02 UEE1303(1070) 23 LECTURE 02 UEE1303(1070) 24

6 Dynamic Memory Allocation new Operator

. Only allocate the amount of memory needed . Since pointers can refer to variables… at run-time –no real need to have a standard identifier . Heap (a.k.a. freestore) . Can dynamically allocate variables –reserved for dynamically-allocated  operator new creates variables variables –no identifiers to refer to them –all new dynamic variables consume –just a pointer! memory in freestore . Example: –if too many  could use all freestore int *p1 = new int; memory –creates a new nameless variable, and . C: malloc(), calloc(), realloc(), free() assigns p1 to point to it . C++: new and delete –can be dereferenced with *p1 –use just like ordinary variable

LECTURE 02 UEE1303(1070) 25 LECTURE 02 UEE1303(1070) 26

delete Operator new/delete Example

. De-allocate dynamic memory // declare a pointer and allocate space –when no longer needed double *dpt = new double(0.0); if (dpt == NULL) –return memory to heap/freestore { //no enough memory to be allocated . Example: cout << "Insufficient memory.\n"; exit(1); int* p = new int(5); //allocate an int } ... //some processing *dpt = 3.4; //use pointer to access value delete p; //delete space that p points to cout << *dpt << endl; //return the space to heap –de-allocate dynamic memory pointed to by delete dpt; pointer p . if new succeeds, program continues; if not, –literally destroys memory space exit the program  good to use NULL check

LECTURE 02 UEE1303(1070) 27 LECTURE 02 UEE1303(1070) 28

7 Memory Leaking illustration of Memory Leaking

. A very common type of error ptr 1st block –may result in memory resource problem 15 . A memory leak occurs when a pointer points to another block of memory without the delete statement that frees the previous block ptr 1st block is lost! . Example: 15 int *ptr = new int; //allocate 1st block *ptr = 15; //access 1st block //not delete the space of 1st block 2nd block ptr = new int; //allocate 2nd block *ptr = 7; //access 2nd block 7 –no way to access the space of 1st block LECTURE 02 UEE1303(1070) 29 LECTURE 02 UEE1303(1070) 30

Standard vs. Dynamic Arrays Create Dynamic Arrays

. Standard array limitations . Use new operator –must specify size first  estimate –dynamically allocate with pointer variable maximum –treat like standard arrays –may not know until program runs! . Example: –waste memory int iSize = 0; . Example: cin >> iSize; double* DoublePtr; const int MAX_SIZE = 100000; DoublePtr ; int iArray[MAX_SIZE]; d = new double[iSize]; //size in brackets

–what if the user only need 100 integers? –create a dynamical array variable d . Dynamic arrays –contain iSize elements of type double –can grow and shrink as needed

LECTURE 02 UEE1303(1070) 31 LECTURE 02 UEE1303(1070) 32

8 Delete Dynamic Arrays Dynamic Multi-dimensional Arrays

. Allocated dynamically at run-time . Multi-dimensional arrays are arrays of arrays –so should be destroyed at run-time –various ways to create dynamic multi- . Continue the previous example: dimensional arrays de-allocate memory for a dynamic array . Example: ... declare one array m of 3 IntArrayPtr pointers d = new double[iSize]; //size in brackets typedef int* IntArrayPtr; ... IntArrayPtr* m = new IntArrayPtr[3]; delete [] d; //delete array that p points for (int idx = 0; idx < 3; idx++) m[idx] = new int[4]; –brackets [] indicate array is there –note that d still points there  dangling! –make each allocated array of 4 integers  should add "d = NULL;" immediately –create one 34 dynamic array

LECTURE 02 UEE1303(1070) 33 LECTURE 02 UEE1303(1070) 34

Two-dimensional Dynamic Arrays Shallow vs. Deep Copies

. Example: . Shallow copy (copy-by-address) int *Mat1[4]; //fix row number at 4 –two or more pointers point to the same for (int r=0; r<4; r++) memory address Mat1[r]=new int[6]; //create 6 columns . Deep copy (copy-by-value) –4 rows , , and Mat1[0] Mat1[1] Mat1[2] –two or more pointers have their own data Mat1[3] are declared . Example: –each row has 6 columns to be created . Example: (most common) int *first, *second; int **Mat2; //2-level pointer first = new int[10]; Mat2=new int *[4]; //create 4 rows second = first; //shallow copy for (int r=0; r<4; r++) second = new int[10]; Mat2[r]=new int [6]; //create 6 columns for (int idx=0;idx<10;idx++) //deep copy –both Mat2 and *Mat2 are pointers second[idx] = first[idx];

LECTURE 02 UEE1303(1070) 35 LECTURE 02 UEE1303(1070) 36

9 Delete Dynamic Arrays Expand Dynamic Arrays

. After a dynamic array is of no use any more, . A program can start with a small array and deallocate the memory by delete operation then expands it only if necessary –Clean reversely from last allocated memory . Example: initially MAX is set as 10 int n = 0; . Example: //reallocate a dynamic 5x9 matrix int * ivec = new int [MAX]; while (cin>>ivec[n]) { int** Mat = new int *[5]; //create 5 rows n++; for (int r=0; r<9; r++) if (n>=MAX) { Mat[r] = new int [9]; //create 9 columns MAX *= 2; ... //some processing int * tmp = new int [MAX]; for (int r=0; r<9; r++) //clean columns for (int j=0; j

LECTURE 02 UEE1303(1070) 37 LECTURE 02 UEE1303(1070) 38

Pass Arrays to Function Return Array from Function (1/2)

. When array is passed to a function, only pass . Array type pointers are not allowed as return- the address of the first element type of function . Example: in main function . Example: int max = FindMax(array, size); int [] someFun(...); //illegal in function declaration section . Instead return pointer to array base type: int FindMax(int *array, int size) { ... int * someFun(...); //legal } . Return a integer pointer after function call –parameter receives the address of array –in main (or caller) function, array  val is one pointer –Another form: int * pt = someFun(...); int FindMax(int val[], int size) {} –only one array (address) can be returned!

LECTURE 02 UEE1303(1070) 39 LECTURE 02 UEE1303(1070) 40

10 Return Array from Function (2/2) Allocate C-style Strings

. One more example: . To store an array of C-style strings int *display(); –first declare an array of C-style strings ... –dynamically allocate space for C-style strings int main() { . Example: cout << *display() << endl; } char wd[100]; //one word int *display() { char *wv[50]; //can save 50 words int *pt = new int[2]; while (cin>>wd) { pt[0] = 0; pt[1] = 0; int len = strlen(wd)+1; int b[2] = {10,20}; char *nw = new char [len]; for (int i=0; i<2; i++) strcpy(nw, wd); *pt = b[i]; wv[n] = nw; //wv[0], wv[1], ... return pt; } n++; }

LECTURE 02 UEE1303(1070) 41 LECTURE 02 UEE1303(1070) 42

Summary (1/2) Summary (2/2)

You have reviewed/learned: . Using references and pointer with constants . Fundamentals of C++ pointer –a reference to a constant –operators and expressions for pointers –a pointer to a constant –point to another pointer/array –a constant pointer –void pointers –a constant pointer to a constant –difference between C and C++ pointers . Dynamic memory allocation . References –C/C++ memory allocation –as a reference variables –new/delete operators –pass to functions including constant –memory leaking references –multi-dimensional dynamic arrays –return by functions –pass/return array to/from function

LECTURE 02 UEE1303(1070) 43 LECTURE 02 UEE1303(1070) 44

11