http://cplusplusatoz.blogspot.in/
Table below shows variables a to g along with their values and memory addresses.
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/
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.
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" ;
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 ;
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.
http://cplusplusatoz.blogspot.in/
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/
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.
http://cplusplusatoz.blogspot.in/