Anda di halaman 1dari 13

Pointers in C++

http://cplusplusatoz.blogspot.in/

What are Pointers?


A pointer is a variable, that holds memory address of another variable. Memory address of a variable refers to the location of the variable in memory.

Table below shows variables a to g along with their values and memory addresses.

Memory Address 2000 2002 2004 2006 2008 2010 2012

Variable a=5 b=4 c = 20 d = 35 e = 10 f = 21 g =6

Variable 'a' for example, has a value 5 assigned to it, and has a memory location 2000. Any pointer that points to 'a' will store its memory location i.e. 2000 in it.

http://cplusplusatoz.blogspot.in/

Declaring Pointer Variables


A pointer variable may be declared in the following way: type * var_name ; Where, type - Base type of the pointer, which may be int, float, char or even a user defined type, about which we'll discuss later. var_name - The name of the pointer variable. Note the * (asterisk) that appears before the variable name in case of pointer declaration. Note: It is essential to declare the type of the pointer same as that of the variable to which it will be pointing. A pointer variable ptr that points to a variable of int type must itself be a pointer of type int.

Pointer Assignments
You can assign address of a variable to a pointer by using '&' i.e. 'address of' operator. int count = 10 ; int *ptr ; ptr = & count ; // This assigns the memory address of the variable count to ptr.

Note: In the statement above, the memory address of the variable count gets assigned to ptr, not the value of count which is 10. If you try to print the value of ptr using cout, then memory address of variable count will get printed. cout << ptr ; // prints the memory address of count, not its value (10). Output will be: 004FF940. (Address value will vary on your computer).

http://cplusplusatoz.blogspot.in/

Note: You cannot assign any value to a pointer variable. You can only extract address of a variable using & operator and assign it to a pointer variable. Or, you can also assign a pointer of the same type another pointer. int *ptr1, *ptr2, count = 10 ; ptr1 = 100 ; // This is an INVALID statement and will result in an error. ptr1 = & count ; // A VALID statement ptr2 = ptr1 ; // A VALID statement. Now both ptr1 and ptr2 point to the same variable, count.

Accessing Variables using Pointers


It is understood by now that if we try to print a pointer variable using cout, the memory address of the variable it points to gets printed, not the value of the pointed variable. Then how can we access the value of the variable to which a pointer points? The answer is simple, by using '*' (indirection) operator. int count = 10 ; int *ptr ; ptr = & count ; cout << ptr << endl ; // prints memory address of count. cout << *ptr ; // prints the value of variable count. Output will be: 004FF940 10 '*' is read as 'value stored at'. That way, *ptr refers to the value stored at ptr and ptr currently stores the memory address of count. So, *ptr refers to value stored at address of count, i.e nothing by count, equal to 10.

http://cplusplusatoz.blogspot.in/

Note: You can use pointers to access variables in expressions along with non pointer variables. For example, the code fragment int count = 10, inc = 20, sum = 0, *ptr ; ptr = &count; sum = inc + *ptr ; // Equivalent to : sum = inc + count cout << sum ; is perfectly valid and results in assignment of the sum of inc and count to the variable sum. You may even read the value of a variable using pointer in the following way : cin >> *ptr ; // Reads the value of variable pointed by ptr from the user.

Pointer Arithmetic
Limited number of Arithmetic operations can be applied on Pointer variables. The Base Type of pointer variable plays a vital role in pointer arithmetic.

Increment
You can increment a pointer variable. The increment is done relative to the base type. For example, If a pointer variable ptr points to a memory location 1000 and ptr is of 'int' type, then ptr ++ ; would increment the value of ptr NOT TO 1001, but to 1002. The reason behind this is that an increment to a pointer variable is interpreted by the Compiler as a request to point to the next variable of the Base Type. Assuming an 'int' variable occupies 2 bytes of memory, the next integer after 1000 will be stored at location 1002. Therefore, increment resulted in the value 1002. If ptr was of float type, the increment would have resulted in the value 1004, assuming float variable occupies 4 bytes of storage.

http://cplusplusatoz.blogspot.in/

Decrement
You can decrement a pointer variable. It would result in the pointer pointing to the previous variable of the Base type. For an int type pointer ptr having pointing to memory address 1002, decrementing will result in it pointing to the memory address 1000, assuming a 2 byte integer. ptr -- ;

Addition/ Subtraction
You may add or subtract integers ( NOT decimal values ) to or from pointer variables. For example, if ptr = 1000 and ptr is of int type, ptr = ptr + 5 ; would result in ptr's value being equal to 1010.

We can generalize this behaviour in the following way : ptr = ptr + value * sizeof( Base Type ) Where, ptr is pointer variable value is the integer to be added or subtracted. That means, whatever value we add or subtract to or from a pointer, that value multiplied by the size of the base type of the pointer gets added or subtracted. In the above example, 5 * 2 gets added, assuming integer of 2 bytes.

http://cplusplusatoz.blogspot.in/

Note: You can NOT add two pointer variables. However, you may subtract a pointer variable from another pointer variable of the SAME type, to know the number of elements of the Base Type that lie between them. For example, if ptr1 points to memory location 2000 and ptr2 points to memory location 1000, and ptr1 and ptr2 are of integer type using 2 bytes, then ptr2 - ptr1 will result in 5, as 5 integers lie between them. This can be calculated by dividing the difference of addresses by the size of the base type.

Comparison
You can also compare two pointers of the same type to see which one of them points to a lower memory location. if ( ptr1 < ptr2 ) cout<< "ptr1 points to a lower memory location" ; else cout<< "ptr2 points to a lower memory location" ;

Pointers & Arrays


There is a very close relationship between Array and Pointers. " The name of an array is a pointer to the first element of the array. " Therefore, if we want to print the first element of an array, we have two options: int arr [10] = {1,2,3,4,5,6,7,8,9,10} ; cout << arr[0] ; // Option 1, using a subscript cout << *arr ; // Option two, using the name of the array as pointer. Both the options will print 1, which is the first element of the array.

http://cplusplusatoz.blogspot.in/

What if we want to display the second value of the array ? We know the if we add 1 to a pointer, it will point to the next variable of the same type. We also know that elements of an array are stored in contiguous memory locations. That simply implies that we can access second variable as : cout << * (arr + 1) ; // Equivalent to arr[1].

Which is difference from, cout<< *arr + 1 ; higher than '+'. // Equivalent to arr[0] + 1 as precedence of operator '*' is

In general, to access i th value of an array, we can use : 1. arr[ i ] 2. * (arr + i ) Both are equivalent. Here 'arr' can be a pointer that points to the first element of an array or the name of the array itself.

Note: You cannot increment or decrement the name of an array. int arr [10] = {1,2,3,4,5,6,7,8,9,10} ; arr ++; // Invalid statement, results in Error. You can however assign the value of arr to another pointer and increment it. int *ptr = arr ; ptr ++ ; // Perfectly valid and ptr now points to the second element of the array // ( the one after the first element's location).

http://cplusplusatoz.blogspot.in/

Array of Pointers
Like other variables, you can declare arrays of pointer variables. Every element of the array is then a pointer. For example, int *x[10]; Declares a pointer array which consists of 10 pointers, x[0] through x [9]. To assign address of a variable to a pointer, say x[5], int count = 15 ; x[5] = & count ;

Multiple Indirection (Double Pointers)


You can have a pointer that points NOT to a variable, but to another pointer, which in turn points to a variable. This is called Multiple indirection. The particular example just stated involves a Double pointer. A double pointer is a pointer that points to another pointer variable. int *ptr1, **ptr2, count = 20 ; ptr1 = & count ; // ptr1 stores address of count ptr2 = & ptr1 ; // ptr2 stores address of ptr1 cout << count ; cout << *ptr1 ; cout << **ptr2 ; // A double pointer requires two '*' for indirection.

http://cplusplusatoz.blogspot.in/

You can take multiple indirection to any level. However, more than a pointer to a pointer is seldom needed. It involves a risk of Logical Errors. int *ptr1, **ptr2, ***ptr3, ****ptr4, var=10 ; ptr1 = & var ; // ptr1 stores address of var ptr2 = & ptr1 ; // ptr2 stores address of ptr1 ptr3 = & ptr2 ; // ptr3 stores address of ptr2 ptr4 = & ptr3 ; // ptr4 stores address of ptr3 cout << var ; cout << * ptr1 ; cout << ** ptr2 ; cout << *** ptr3 ; cout << **** ptr4; // Number of '*' used corresponds to the level of indirection. The above code fragment is valid but NOT RECOMMENDED due to a high degree of indirection.

Dynamic Arrays Using pointers and new and delete Operators


The arrays we've used so far were static. We needed to specify their size in our code. This has two disadvantages: a. Statically allocated memory might be insufficient at run time, if need for more than allocated storage space is required. b. Statically allocated memory might be much more than required. This wastes useful memory which could have been used for other purposes. So, C++ supports Dynamic Arrays for the purpose. You can define at Run Time, the number of elements required. You may even change size of an array during Run Time. We'll discuss Dynamic Allocation in greater detail later. Here we only discuss how to create arrays with their size being decided at Run-time.

http://cplusplusatoz.blogspot.in/

The new Operator


The new operator is used to allocated memory dynamically. Its structure is as follows : ptr = new type [ size ] ; omitted. ptr = new type ; // For Array. In case of a single variable, [ size ] can be

// For a single variable.

Where, ptr is a pointer variable type is the base type to be used (int, float, etc) size is the number of elements of the base type required. The new operators allocates the requested memory and returns the memory address of the first location that was allocated. This address gets assigned to ptr. Since memory is limited, rarely, there might be a case in which there is not enough memory to allocate. In that case, bad_alloc exception will be generated. If your program does not handle this exception, then it will terminate. This exception is defined in the header <new>. We'll discuss Exception Handling in greater detail later. Note: Old compilers did not use this exception handling mechanism. The only way to know whether the memory has been allocated was to check the pointer returned by new operator. If it was NULL, it meant memory could not be allocated. You must check your compiler's documentation to know how your compiler behaves. It is possible that your compiler makes new return NULL in case of failure and also generates a bad_alloc exception.

If you want new operator to return NULL instead of throwing an exception bad_alloc, you can use the nothrow alternative : ptr = new (nothrow) type ; Now, the new operator will return NULL pointer in case of failure and it will not generate any exception. This has advantage of being useful when porting C code to C++. To use this feature, you have to include the header <new>.
http://cplusplusatoz.blogspot.in/

The delete Operator


It is your responsibility to free the memory allocated by you Dynamically using the new operator. You can do this by using delete operator. delete ptr ; // When ptr points to a single variable of any type.

delete [] ptr ; // When ptr points to an array of elements.

Array using new operator


int *arr ; int size ; cout << "Enter size of the array : "; cin >> size ; arr = new int [size] ; cout << "Enter array elements: " ; for( int i = 0 ; i < size ; i ++ ) cin>>arr[i] ; // equivalent to : cin >> *(arr + i ) ; cout << "Elements entered are: "; for( int i = 0 ; i < size ; i ++ ) cout << arr[i] ; // equivalent to : cout << *(arr + i ) ;

Advantages of Pointers
1. Pointers support Dynamic Allocation. 2. Pointers may improve efficiency of certain programs. 3. Pointers allow functions to modify their calling arguments. (We'll discuss this in greater detail when we study functions.)

http://cplusplusatoz.blogspot.in/

Disadvantages of Pointers
1. Errors that arise due to pointers are difficult to track. 2. Unassigned pointers or incorrectly assigned pointers may lead to system crashes. Although Exception Handling can be used to prevent such a situation.

Practice Program
Write a Program to swap two numbers using pointers. #include <iostream> using namespace std; void main() { int *ptr1, *ptr2, var1, var2, temp ; cout<<"Enter var1: "; cin>>var1; cout<<"Enter var2: "; cin>>var2; ptr1 = & var1 ; ptr2 = & var2 ; cout<<"Swapping..."<<endl; temp = *ptr1 ; *ptr1 = *ptr2 ; *ptr2 = temp ; cout<<"var1: "<<var1<<endl<<"var2: "<<var2<<endl; system("Pause"); }

http://cplusplusatoz.blogspot.in/

OUTPUT

Note: Any questions related to this or any other topic are welcome.

For more articles, visit: http://cplusplusatoz.blogspot.in/

http://cplusplusatoz.blogspot.in/

Anda mungkin juga menyukai