Pointer, Arrays, Pointer Arithmetic - Exam 1 | CSCI 1200, Exams of Data Structures and Algorithms

Material Type: Exam; Class: DATA STRUCTURES; Subject: Computer Science; University: Rensselaer Polytechnic Institute; Term: Fall 2008;

Typology: Exams

Pre 2010

Uploaded on 08/09/2009

koofers-user-wbu
koofers-user-wbu 🇺🇸

5

(1)

9 documents

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CSCI-1200 Computer Science II Fall 2008
Lecture 5 Pointers, Arrays, Pointer Arithmetic
Announcements: Test 1 Information
Test 1 will be held Tuesday, September 16th, 2008 from 2-3:50pm in West Hall Auditorium. No
make-ups will be given except for emergency situations, and even then a written excuse from the Dean of
Students office will be required.
Coverage: Lectures 1-6, Labs 1-3, HW 1-2.
Closed-book and closed-notes except for 1 sheet of notes on 8.5x11 inch paper (front & back) that may be
handwritten or printed. Computers, cell-phones, palm pilots, calculators, PDAs, music players, etc. are not
permitted and must be turned off.
All students must bring their Rensselaer photo ID card.
Practice problems from previous exams will be available on the course website. Solutions to the problems will
be posted later.
Review from Last Week
C++ class syntax, designing classes, classes vs. structs; Passing comparison functions to sort; Non-member
operators.
Today’s Lecture Pointers and Arrays
Optional Reading: Ford & Topp pp. 219-228; Koenig and Moo, Section 10.1
Pointers store memory addresses.
They can be used to access the values stored at their stored memory address.
They can be incremented, decremented, added and subtracted.
Dynamic memory is accessed through pointers.
Pointers are also the primitive mechanism underlying vector iterators, which we have used with std::sort and
will continue to use many times throughout the semester.
5.1 Pointer Example
Consider the following code segment:
float x = 15.5;
float *p; /* equiv: float* p; */
p = &x;
*p = 72;
if(x>20)
cout << "Bigger\n";
else
cout << "Smaller\n";
The output is Bigger
because x == 72.0. What’s going on?
Computer memory
Before *p=72
p
x
After *p=72
p
x72.0
15.5
5.2 Pointer Variables and Memory Access
xis an ordinary integer, but pis a pointer that can hold the memory address of an integer variable. The
difference is explained in the picture above.
Every variable is attached to a location in memory. This is where the value of that variable is stored. Hence,
we draw a picture with the variable name next to a box that represents the memory location.
pf3
pf4
pf5

Partial preview of the text

Download Pointer, Arrays, Pointer Arithmetic - Exam 1 | CSCI 1200 and more Exams Data Structures and Algorithms in PDF only on Docsity!

CSCI-1200 Computer Science II — Fall 2008

Lecture 5 — Pointers, Arrays, Pointer Arithmetic

Announcements: Test 1 Information

  • Test 1 will be held Tuesday, September 16th, 2008 from 2-3:50pm in West Hall Auditorium. No make-ups will be given except for emergency situations, and even then a written excuse from the Dean of Students office will be required.
  • Coverage: Lectures 1-6, Labs 1-3, HW 1-2.
  • Closed-book and closed-notes except for 1 sheet of notes on 8.5x11 inch paper (front & back) that may be handwritten or printed. Computers, cell-phones, palm pilots, calculators, PDAs, music players, etc. are not permitted and must be turned off.
  • All students must bring their Rensselaer photo ID card.
  • Practice problems from previous exams will be available on the course website. Solutions to the problems will be posted later.

Review from Last Week

  • C++ class syntax, designing classes, classes vs. structs; Passing comparison functions to sort; Non-member operators.

Today’s Lecture — Pointers and Arrays

Optional Reading: Ford & Topp pp. 219-228; Koenig and Moo, Section 10.

  • Pointers store memory addresses.
  • They can be used to access the values stored at their stored memory address.
  • They can be incremented, decremented, added and subtracted.
  • Dynamic memory is accessed through pointers.
  • Pointers are also the primitive mechanism underlying vector iterators, which we have used with std::sort and will continue to use many times throughout the semester.

5.1 Pointer Example

  • Consider the following code segment:

float x = 15.5; float p; / equiv: float* p; */ p = &x; *p = 72; if ( x > 20 ) cout << "Bigger\n"; else cout << "Smaller\n";

The output is Bigger because x == 72.0. What’s going on? Computer memory

Before *p=

p

x

After *p=

p

15.5 x 72.

5.2 Pointer Variables and Memory Access

  • x is an ordinary integer, but p is a pointer that can hold the memory address of an integer variable. The difference is explained in the picture above.
  • Every variable is attached to a location in memory. This is where the value of that variable is stored. Hence, we draw a picture with the variable name next to a box that represents the memory location.
  • Each memory location also has an address, which is itself just an index into the giant array that is the computer memory.
  • The value stored in a pointer variable is an address in memory. The statement p = &x; takes the address of x’s memory location and stores it (the address) in the memory location associated with p.
  • Since the value of this address is much less important than the fact that the address is x’s memory location, we depict the address with an arrow.
  • The statement: *p = 72; causes the computer to get the memory location stored at p, then go to that memory location, and store 72 there. This writes the 72 in x’s location. Note: *p is an l-value in the above expression.

5.3 Defining Pointer Variables

  • In the example below, p, s and t are all pointer variables (pointers, for short), but q is NOT. You need the * before each variable name.

int * p, q; float *s, *t;

  • There is no initialization of pointer variables in this two-line sequence, so a statement below is dangerous, and may cause your program to crash! (It won’t crash if the uninitialized value happens to be a legal address.)

*p = 15;

5.4 Operations on Pointers

  • The unary operator * in the expression *p is the “dereferencing operator”. It means “follow the pointer” *p can be either an l-value or an r-value, depending on which side of the = it appears on.
  • The unary operator & in the expression &x means “take the memory address of.”
  • Pointers can be assigned. This just copies memory addresses as though they were values (which they are). Let’s work through the example below. What are the values of x and y at the end?

float x=5, y=9; float *p = &x, *q = &y; *p = 17.0; *q = *p; q = p; *q = 13.0;

  • Assignments of integers or floats to pointers and assignments mixing pointers of different types are illegal. Continuing with the above example:

int *r; r = q; // Illegal: different pointer types; p = 35.1; // Illegal: float assigned to a pointer

  • Comparisons between pointers of the form if ( p == q ) or if ( p != q ) are legal and very useful! Less than and greater than comparisons are also allowed. These are useful only when the pointers are to locations within an array.

5.5 Exercise

  • What is the output of the following code sequence?

int x = 10, y = 15; int *a = &x; cout << x << " " << y << endl; int *b = &y; *a = x * *b; cout << x << " " << y << endl; int *c = b; *c = 25; cout << x << " " << y << endl;

5.9 Sorting an Array

  • Arrays may be sorted using std::sort, just as vectors may. Pointers are used in place of iterators. For example, if a is an array of doubles and there are n values in the array, then here’s how to sort the values in the array into increasing order:

std::sort( a, a+n )

5.10 Exercises

For each of the following problems, you may only use pointers and not subscripting:

  1. Write code to print the array a backwards, using pointers.
  2. Write code to print every other value of the array a, again using pointers.
  3. Write a function that checks whether the contents of an array of doubles are sorted into increasing order. The function must accept two arguments: a pointer (to the start of the array), and an integer indicating the size of the array.

5.11 Character Arrays and String Literals

  • In the line below "Hello!" is a string literal and it is also an array of characters (with no associated variable name).

cout << "Hello!" << endl;

  • A char array can be initialized as: char h[] = {’H’, ’e’, ’l’, ’l’, ’o’, ’!’, ’\0’}; or as: char h[] = "Hello!"; In either case, array h has 7 characters, the last one being the null character.
  • The C and C++ languages have many functions for manipulating these “C-style strings”. We don’t study them much anymore because the standard string library is much more logical and easier to use.
  • One place we do use them is in file names and command-line arguments, as you have already seen.

5.12 Conversion Between Standard Strings and C-Style String Literals

  • We have been creating standard strings from C-style strings all semester. Here are 2 different examples:

string s1( "Hello!" ); string s2( h );

where h is as defined above.

  • You can obtain the C-style string from a standard string using the member function c_str, as in s1.c_str().

5.13 C Calling Convention

  • A calling convention is a standardized method for passing arguments between the caller and the function. Calling conventions vary between programming languages, compilers, and computer hardware.
  • In C on x86 architectures here is a generalization of what happens:
    1. The caller puts all the arguments on the stack, in reverse order.
    2. The caller puts the address of its code on the stack (the return address).
    3. Control is transferred to the callee.
    4. The callee puts any local variables on the stack.
    5. The callee does its work and puts the return value in a special register (storage location).
    6. The callee removes its local variables from the stack.
    7. Control is transferred by removing the address of the caller from the stack and going there.
    8. The caller removes the arguments from the stack.
  • On x86 architectures the addresses on the stack are in descending order. This is not true of all hardware.

5.14 Poking around in the stack

int foo(int a, int *b) { int q = a+1; int r = *b+1; cout << "address of a = " << &a << endl; cout << "address of b = " << &b << endl; cout << "address of q = " << &q << endl; cout << "address of r = " << &r << endl; cout << "value at " << &a << " = " << a << endl; cout << "value at " << &b << " = " << b << endl; cout << "value at " << b << " = " << b << endl; cout << "value at " << &q << " = " << q << endl; cout << "value at " << &r << " = " << r << endl; return qr; }

int main() { int x = 5; int y = 7; int answer = foo (x, &y); cout << "address of x = " << &x << endl; cout << "address of y = " << &y << endl; cout << "address of answer = " << &answer << endl; cout << "value at " << &x << " = " << x << endl; cout << "value at " << &y << " = " << y << endl; cout << "value at " << &answer << " = " << answer << endl; }

Sample Output

address of a = 0x23eef address of b = 0x23eef address of q = 0x23eee address of r = 0x23eee value at 0x23eef0 = 5 value at 0x23eef4 = 0x23ef value at 0x23ef10 = 7 value at 0x23eee4 = 6 value at 0x23eee0 = 8 address of x = 0x23ef address of y = 0x23ef address of answer = 0x23ef0c value at 0x23ef14 = 5 value at 0x23ef10 = 7 value at 0x23ef0c = 48

answer=

0x23ef

48

0x23ef 0x23ef 0x23ef0c 0x23ef 0x23ef 0x23ef 0x23eefc 0x23eef 0x23eef 0x23eef 0x23eeec 0x23eee 0x23eee 0x23eee 0x23eedc 0x23eed

0x23ef 5 7

5

6 8

y=

x=

b= a=

q= r=