Title: Pointers
1Pointers
- Intro and Syntax
- Dynamic memory allocation and linked lists
- Pointers and arrays memory allocation and
efficiency
2Pointers and Dynamic Arrays
31D arrays with the new operator
- To dynamically allocate an array, specify the
array size in square - brackets after the type
- int ptr
- ptr new int 20 // dynamically
allocate enough - // memory for an array of 20 ints.
- // IntArrayPtr now points to the
- // 1st element of the array.
- tvectorltDice gt dices(6) //array of pointers to
6 dice objects - do not free! - //you are not responsible of grayed lines or
code - To delete a dynamically allocated array, you must
include a pair of empty - square brackets in the delete statement, just
after the delete command -
- delete ptr //Use - no matter how many
dimensions -
ptr
4Memory allocation with the new operatorPoints to
be careful for
- What happens if you dont have enough memory?
- NULL pointer is returned
- You need to check for that possibility
- int ptr
- ptr new int 100000
- if ( ptr ! NULL)
- ...
- Why would this happen?
5Memory allocation with the new operatorPoints to
be careful for
- Dice MakeDie(int n)
- //return pointer to n sided object
-
- Dice nSided(n)
- return nSided
-
- Dice cube MakeDie (4)
- Dice tetra MakeDie (6)
- Cout ltlt cube-gtNumSides()
What is the problem?
Error message address of local variable returned
6Memory allocation with the new operator
- What is the problem?
- Dice MakeDie(int n)
- //return pointer to n sided object
-
- Dice nSided(n) nsided
- return nSided
-
- Dice cube MakeDie (4) cube
- Dice tetra MakeDie (6)
- Cout ltlt cube-gtNumSides()
Returning a pointer to a variable on the stack
(with the operator), is wrong!
no longer exists after the function returns
7Memory allocation with the new operator
- Solution
- Dice MakeDie(int n)
- //return pointer to n sided object
-
- Dice dice_ptr new Dice (n) dice_ptr
- return dice_ptr
-
- Dice cube MakeDie (4) //cube
- Dice tetra MakeDie (6)
- Cout ltlt cube-gtNumSides()
- //Is there any problem left?
8Using Pointers good practices
- C allows programmers to define new types
(actually an alias for a type) using the typedef
statement -
- typedef int IntPtr
- IntPtr p1, p2
-
- Why would you do this?
-
-
9Using Pointers good practices
- typedef int IntPtr
- IntPtr p1, p2
-
- Avoids mistake of forgetting the
- int p1, p2
-
- Simpler to use call-by-reference pointer variable
(needed if use new within a function) -
- void get_space(IntPtr ptr)
- //void get_space(int ptr)
-
10Pointers and 2D Dynamic Arrays
11- We want to allocate for a very big 2Dimensional
matrix of integers. - Lets call this nums.
- We dont want to make an assumption on how big
this matrix might be (put a limit or use a very
big matrix, just in case), instead, we want to
allocate the matrix dynamically.
12Dynamic allocation two dimensional arrays
- int nums
- int rows, columns, I,j
-
- coutltlt "Enter the number of rows "
- cin gtgt rows
- coutltlt "Enter the number of columns "
- cin gtgt columns
-
- // nums is an array of int pointers
- nums new int rows
- // each nums i is an array of ints.
- for (i 0 iltrows i)
- numsi new int columns
-
cout ltlt "Enter the elements" ltlt endl for (i
0 i lt rows i) for (j 0 jlt columns j)
coutltlt '' ltlt i ltlt ',' ltlt j ltlt " " cin
gtgt numsij coutltlt endl
print_table(nums, rows, columns) //
Returning memory to free heap for reuse for (i
0 ilt rows i) delete numsi
delete nums
13Dynamic allocation two dimensional arrays
- void print_table(int values,
- int num_rows, int num_cols)
-
- int i, j
-
- for (i 0 i lt num_rows i)
- for (j 0 jlt num_cols j)
- cout ltlt valuesij ltlt " "
- cout ltlt endl
-
-
-
14Classes with pointers
- Example image class
- class img
- private
- int width
- int height
- int data
- public
- img (const int w, const int h)
- ...
imgimg (const int w, const int h) data new
int h //generates the array for h rows of
pointers //each cell is of type int for (int
i0 i lt h i) datai new int
w //each cell of the row array is int ...
15Another more complicated example
- Task You want to store a list of words in a data
structure, but the words vary in length greatly - (3 letters to 60 letters).
- Desired What you really want is a data structure
like an array where each cell is of variable
length (so that you dont have to use the max
length of 60 for every cell). - Solution What you can use is an array of char
pointers, and allocate variable length chars to
each cell. - Note that you can look at this as a1D array of
char strings or 2D arrays of chars -
-
-
gelebilecekdiyseler
zil
16Another more complicated example
-
- char wordlist10000
- char wordMAX_WORD_LENGTH //allocate temp
char string - for (i0 i lt 10000 i)
- //get the next word
- cin gtgt word
- wordstrlen(word) '\0'
- wordlisti new charstrlen(word)
- strcpy(wordlisti,word)
-
- //note that we enter word as a char string use
the familiar strlen function - What is the advantage over an array of fixed
- size character arrays?
-
gelebilecekdiyseler
zil
17Pointers and Static Arrays
18Pointers and Arrays
- int myarray10
- int ptr
- ptr myarray // address stored in pointer
is the address of the first element in array - Or
- ptr myarray0 //equivalently (more clear)
19Pointers and Arrays Increment
- int students10
- int ptr
- ptr students //ptr points to students 0
- ptr students0 //same as above
- ptr
- int p_tmp
- p_tmp ptr // p_tmp points to students 1
- I.e. ptr increments go by the size of the type
pointed by the pointer - in this case the pointer points to 4 bytes ahead
(not 1 byte) to the next integer
20Pointer Increment Depends on Pointed Type
- char c c
- char p //p points nowhere
- p c // p now points to c.
- p-- // p now points to the address of the byte
before c - p // p points to c again.
- If the pointer pointed to integers
- int myintarr 20
- int p myintarr
- p // p now points to 4 bytes ahead (when
ints takes 4 bytes) - This is the reason why we dont just say pointer
p - We want the compiler to move the pointer by the
size of the data type it points to.
21Pointers and Arrays Examples
- const int NUM_STUDENTS 10
- int studentsNUM_STUDENTS
- int p
- p students // address stored in pointer is
that of the - // first element in array.
- for (i0 i lt NUM_STUDENTS i)
- cout ltlt studentsi
- or
- for (i0 i lt NUM_STUDENTS i)
- cout ltlt p
2nd one is often much more efficient (use this
from now on)!! - incrementing is faster than
addition (arrayi is found as offset from
array0 - also when array indexing is more
complex (more complicated offsets...), pointers
are even more efficient
22Pointers and Arrays Examples
- Typical array/string copying routine
- Note that memory for destination is allocated in
the calling program - char my_strcpy (char destination, char
source) -
- char p destination
- while (source ! '\0')
- p source //I had told you
not to use cryptic code - //but this piece of code is very common that
everyone can understand it easily -
- p '\0' //why do we need this?
23Ptr use for efficiency - 1
- Assume we have a static 1D array which actually
holds 2D data - unsigned char imgwidthheight //grayscale
image with pixel values 0-255 - Typically, you need to access a certain pixel at
a certain col, row, to do something. For instance
thresholding, i.e. make all light grey background
pure white. - for (row0 row lt height row)
- for (col0 col lt width col)
- if (imgrowwidthcol gt 200)
- imgrowwidthcol
255 //assign a new grey value -
24Ptr use for efficiency - 2
- Assume we have a static 1D array which actually
holds 2D data - unsigned char imgwidthheight //grayscale
image with pixel values 0-255 - Typically, you need to access a certain pixel at
a certain col, row, to do something. For
instance - unsigned char ptr img0
- for (row0 row lt height row)
- for (col0 col lt width col)
- if (ptr gt 200)
- ptr255
- ptr
-
-
- How much savings?? Where do you get the gain?
25Another use of pointers
- Imagine sorting an array, whose elements are
structs with lots of data in them. - e.g. StudentRecord students 1000 //assume
StudentRecod is huge - - Swapping individual array elements takes a
long time. - - Instead, swap pointers pointed to array
elements
...
Ziya ... Ahmet .. Derya ...
Banu... Transcript...
Transcript ...
26Pointers summary
- a pointer stores the address of a dynamically
allocated memory location - In C we have mechanisms
- to create pointers ( lttypegt ptr )
- to dynamically allocate memory (new statement)
- to make a pointer points to such a memory
location (using assignment operator) - to manipulate the content of a memory location
via pointers ( operator) - to free dynamically allocated memory (delete
statement)