Lecture 9

# The new variable does not have a name and is not

This preview shows page 1. Sign up to view the full content.

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

Unformatted text preview: EXAMPLE: ptr = new int; How do we use the new variable? The new variable does not have a name and is not declared. ptr Brand New Integer Variable C++ will use the new variable if we write *ptr 13 CREATING A NEW VARIABLE int *ptr; 14 Example: // declares ptr as a pointer // value of ptr is undefined *ptr = 5; // Wrong! only a pointer was // declared, not the storage space. ptr = new int;// ptr points to an integer now. // Space for the integer was just // allocated using “new” *ptr = 5; // Right! ptr points to an integer. int *p, *q; p = new int; *p = 99; // Two pointers // Allocate storage // Assign value What is the effect of q = p; ? 15 p Brand New integer variable 16 Now a brand new example: (We start from scratch) q int *p, *q; p = new int; q = new int; *p = 88; *q = *p; 99 17 18 p What would happen if we would have done q q = p; 88 88 instead of *q = *p? 19 20 Arrays and Pointers Assuming int v[50]; int *vptr = v; p q 88 v is equivalent to &v[0] vptr = v; is equivalent to vptr = &v[0]; vptr+5 is equivalent to &v[5] *(vptr+5) is equivalent to v[5] LOST! Can not be recovered! 21 NULL POINTER When a pointer is declared, just where this pointer is pointing is undefined. To be safe, the pointer should be assigned the value 0 (NULL). This assures the pointer is not pointing anywhere it shouldn’ be. Also, this helps t determine whether a pointer has been assigned or not. if (ptr = = 0) cout << “ptr not assigned”; 23 In functions, arrays are passed as pointers. Why is this? 22...
View Full Document

## This document was uploaded on 03/31/2014 for the course CS 114 at NJIT.

Ask a homework question - tutors are online