Docsity

CGS 3460 Lecture 31: Arrays, Pointers, and Dynamic Memory Allocation, Study notes of Computer Science

Partial preview of the text

Download CGS 3460 Lecture 31: Arrays, Pointers, and Dynamic Memory Allocation and more Study notes Computer Science in PDF only on Docsity!

Pointer andDynamic AllocatedMemoryCGS 3460, Lecture 31Mar 29, 2006Hen-I Yang

Announcement „^ Corrupted Tar file will result in 5-pointpenalty starting from Homework 5 „^ Logistics of Homework 4 + 5 „^ Restructure of the homework descriptionwebpages

Dos „^ Group discussion about the strategy to solve theproblem, e.g.^

^

Step 1, calculate adjacent matrix Step 2, go into infinite loop and receive players’ input … „^ Discussion about how to use certain features ofC „^ Ask TA, myself, tutoring center „^ Send questions to mailiing lists „^ Check Textbook „^ Look at sample code or hints „^ Discuss with classmates in library, E309, etc.Discuss over the phone.

Homework 5 „^ Webpage „^ You’ll be given test cases for homework 4 „^ Sample code from homework 4 will not beavailable until mid-April „^ The grading criteria for correctness/othersis changed to 50% each for this homework „^ A maximum of 110 points for taking theroad less traveled.

Agenda „^ Arrays and Pointers „^ Dynamic Memory Allocation „^ Dynamic Allocated Arrays „^ Deallocation

How do these pointers work? „^ *p++,

*(p++)

„^ (*p)++ „^ *++p,

*(++p)

„^ ++*p,

++(*p)

Array and Pointer (IV) „^ Declaration: int a[10] is not equal to int *a „^ if^ p

=^

a;^ can we use p[2] to point to the

third element in array a?

Multidimensional Array andPointers (I) „^ Pointers can point tomultidimensionalarrays too „^ Row major^ ^

E.g. char A[3][3]

A[2][3] A[2][2] A[2][1] A[2][0]

A[1][3] A[1][2] A[1][1] A[1][0]

A[0][3] A[0][2] A[0][1] A[0][0]

p A[0][0]A[0][1]A[0][2]A[0][3]A[1][0]A[1][1]A[1][2]A[1][3]A[2][0]A[2][1]A[2][2]A[2][3]

*int a[10][10] = {0,1,0,1,0,1,0,1};int p;for (row = 0; row < 10; row++)

for (column = 0; column < 10; column++)a[row][column] = 0; for (p = &a[0][0]; p <= &a[9][9]; p++)

*p = 0;

Equivalent

Multidimensional Array andPointers (III)

Multidimensional Array andPointers (IV) „^ Remember if „^ int a[10]; „^ Then automatically pointer a points to a[0] „^ (a is equivalent to &a[0])^ „^ What about^ „^ int b[10][10];^ „^ Is there an automatic pointer b?^ „^ Yes, but b = &b[0], not &b[0][0]^ „^ b is of type (int **) !! Pointer of pointers

  • Before you go „ Read Chapter 17 „ Exercise: Have a look at 17.4 „ Quiz 4 on March 31, Friday, at the beginning ofthe class. „ Quiz 4 covers chapter 7 – 9, homework 4, slidesup to Lecture 26 „ Homework 4 submission on March 31, Friday at11:59 pm „ No late submission for homework