Initializing Pointers


There is one last, but critical issue to address regarding pointers. Before you use a pointer you must initialize it. You initialize a pointer in one of two ways. The most common way is to set the pointer equal to the address of some standard variable. With pointers to standard variable types you can also set the pointer equal to 0, as in the following example.

int *ptr = 0;

If you attempt to utilize a pointer that has not been initialized, by one method or the other, then you will generate an exception and probably crash your program. Because a pointer is a reference to an address in memory, if you don’t initialize it then it is pointing to some indeterminate address in memory. The following short example illustrates what happens when you use a pointer that has not been initialized.

Example 9.5

Step 1: Type the following code into your favorite text editor.

#include <iostream> using namespace std;   struct account {  int accountnum;  float balance;  float interestrate; }; int main() {  account myaccount; account *ptraccount; ptraccount->balance = 1000;      return 0;   }

Step 2: Compile that code.

Step 3: Run the code. You should see something like what is shown in Figure 9.6.

click to expand
Figure 9.6: Using a pointer that is not initialized.

It is absolutely critical that you do not use a pointer that has not been initialized.




C++ Programming Fundamentals
C++ Programming Fundamentals (Cyberrookies)
ISBN: 1584502371
EAN: 2147483647
Year: 2005
Pages: 197
Authors: Chuck Easttom

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net