# Lec23 - 1 Lecture 23 Pointers and Arrays PIC 10A Todd...

This preview shows pages 1–3. Sign up to view the full content.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1 Lecture 23: Pointers and Arrays PIC 10A Todd Wittman An experiment s Suppose we have an array a. int a[10]; s To see its values, we have to print them one at a time in a loop. for (int i=0; i<10; i++) cout << a[i] << " "; s But what happens if we try just cout << a; s It will print the hexadecimal memory address of the array (e.g. 139AD3C). s This is actually the address of the first block in the array &a[0]. We could store this in a pointer. 2 Pointers and Arrays s When we set a pointer equal to an array name (not the address), it actually points to the first element of the array. int a[5] = {10,20,30,40,50}; int* p = a; //Now p points to a[0]. cout << a[0] << “\n”; cout << *p << “\n”; s We can increment the pointer, so that it goes to the next element of the array. p++; //Now p points to next element a[1]. cout << a[1] << “\n”; cout << *p << “\n”; cout << *(p+2); Both print out the first element 10 Both print out the second element 20 What does this print out? 10 20 30 40 50 p 10 20 30 40 50 p Pointers and Arrays s Ex Given a pointer to the start of an array, write a function that prints out the elements of the array. void printArray( int* p, int array_size) { for (int i = 0; i < array_size; i++) { cout << *p << " "; p++; } return; } int a[5] = {10,20,30,40,50}; int* p = a; printArray (p, 5); cout << “\n” << *p; What’s the output?...
View Full Document

## This note was uploaded on 04/27/2010 for the course PIC 157-050-21 taught by Professor Wittman during the Fall '10 term at UCLA.

### Page1 / 8

Lec23 - 1 Lecture 23 Pointers and Arrays PIC 10A Todd...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online