Pointers in C++

A pointer is an expression that denotes both the address and type of an additional object. By using the address operator, &, for a given object generates a pointer to that object. Assumed that var is an int variable,
E.g.: &var // the Address of the object var
Here is the address of the int object in memory. Accordingly a pointer to var. A pointer points to a memory address and concurrentlyspecifies by its type how the memory address can be read or else written to. Therefore, depending on the type, we bring up to pointers to char and int, or use an abridgement, such as char pointer, int pointer, etc.

Null pointers
• Just like normal variables, pointers are not set when they are instantiated.a pointer will get to some garbage address by default.
• Also memory addresses, there is one additional value that a pointer can hold i.e. a null value. A null value is a different value that is the pointer is not indicating at anything. Hence, A pointer holding a null value is characterized a null pointer.
• In C++, we can assign a pointer a null value by changingor elsepassing on it to the literal 0:

int *ptr(0);  // ptr is currently a null pointer
 
int *ptr2; // ptr2 is uninitialized
ptr2 = 0; // ptr2 is here a null pointer

• By means of a null pointer calculates to 0, it can be used inside a conditional .

double *ptr(0);
 
if (ptr)
    cout<< "ptr is pointing to a double value.";
else
    cout<< "ptr is a null pointer.";

• no other valid pointer, to any other variable or else array cell will ever equal to a null pointer.
• to “get” a null pointer in your program the predefined constant NULL is used.
• To alter a pointer to a null pointer,we can write,
#include

int *ip = NULL;
• It is also conceivable to reference to the null pointer by using a constant 0,
int *ip = 0;

Pointer arithmetic

The C++ language lets you to do integer addition or subtraction operations on pointers. If ptr points to an integer, ptr + 1 is the address of the subsequent integer in memory after ptr. ptr – 1 is the address of the preceding integer before ptr.
Here, ptr + 1 does not return the memory address after ptr, but the memory address of the next object of the type that ptrplugs to. If ptr points to an integer ptr + 3 means 3 integers after ptr. If ptr points to a char, which is at all times 1 byte, ptr + 3 means 3 chars afterptr.
When computing the result of a pointer arithmetic expression, the compiler each time multiplies the integer operand by the size of the object being pointed to. This istermed scaling.

Example:

Output:

• the arrays are in fact just constant pointers with related sizes! They point to the first element in the array, and then just collect the next elements successively in memory up to some sort of terminator in the memory specifies the end of the array.

int array_name[] = {1, 2, 3, 4, 5}; 
cout <<array_name;

• to access the second element in our integer array, we can simply add one to the pointer and then dereference this:

int array_name[] = {1, 2, 3, 4, 5}; 
cout << *(array_name + 1);

• this calculation would be different if we were working openly with the memory addresses

int array_name[] = {1, 2, 3, 4, 5};
cout << *(int*)((long)array_name + sizeof(int)); //The not-so-neat way

Example :

Output :

Here, The good thing about this method of looping through the array is that we’re continuallytotally sure that we’ve gotten the end of the array if we distinguish the terminator is set properly, as there can merely be one byte at the address which the terminator is at, so there is no chance of clash.

Pointer Array
1. A pointer is a place in memory that holds address of another place inside 1. An array is a single, pre allotted piece of contiguous elements i.e.all of the same type, static in size and location.
2. Pointer can’t be retuned at definition.

 

2. Array can be reset at explanation. Example

int num[] = { 3, 4, 5}

3. Pointer is active in nature. The memory setting up can be resized or else freed later. 3. They are fixed in nature. Once memory is allotted, it cannot be resized or else freed dynamically.
4. The assembly code of Pointer is altered than Array 4. The assembly code of Array is varied than Pointer.
sizeof(pointer)  returns the amount of memory used by the pointer variable itself

 

5. the sizeof operator
o sizeof(array) returns the amount of memory used by altogether elements in array
6. &array[0] returns the address of the very 1stelement in array 6. &pointer yields the address of pointer
7. char array[] = “abc” groups elements in array to ‘a’, ‘b’, ‘c’, plus ‘\0’ 7. char *pointer = “abc” cliques pointer to the address of the “abc” string

Array of pointers

  • We know ,sorting an array of strings needs swapping the strings which can entail copying a lot of data. For adeptness, it is better to escape actual swapping of data whenever a data item is huge.In a nutshell it is necesarry to use pointers to elements of the array also swap pointers.

examples:

int data1, data2, *ptr1, *ptr2, *save;

 

data1 = 100; data2 = 200;

ptr1 = &data1; ptr2 = &data2;

here, we could  swap the values of the pointers:

save = ptr1;

ptr1 = ptr2;

ptr2 = save;

We have not altered the values in data1 and data2; but then again ptr1 now accesses data2 and ptr2 access data1. We have swapped the pointer values so they point to objects in a dissimilar order. by applying the same idea to strings:

char name1[] = “John”;

char name2[] = “Dave”;

char *p1, *p2, *save;

 

p1 = name1;

p2 = name2;

Pointers p1 and p2 point to strings name1 and name2. We can at this time swap the pointer values so p1 and p2 point to name2 and name1, correspondingly.

  • so, an array of pointers can be used to point to an array of data items .hereevery element of the pointer array aiming to an element of the data array.
  • Data items can be retrieved either directly in the data array, or else indirectly by dereferencing the elements of the pointer array.
  • Here, the pointers can be rearranged in any manner without affecting the data items. This method saves a lot of time, and the data items keep on available in the original order.
  • Let us see, an array of character pointers to point to the strings stated as follows:

char * nameptr[MAX];

here,The array, nameptr[], of size MAX, and every element of the array is a character pointer. It is then possible to assign character pointer values to the elements of the array; for example:

nameptr[i] = “John Smith”;

The string “John Smith” is placed also the pointer to the string constant is then allotted to nameptr[i].

  • Now, we can recite strings into a two dimensional array, names[][], assigning each string pointer, names[i] to the   element of the pointer array, nameptr[]:

for (i = 0; i< MAX && gets(names[i]); i++)

nameptr[i] = names[i];

 Pointer to pointer

if we use “pass by pointer” to pass a pointer to a function, then a copy of the pointer is passed to the function. In case when you vary the pointer inside the function you are only modifying a copy of the pointer .thus,the original pointer leftovers unmodified. The code below demonstrates this behaviour

Example:

Output:

Syntax of Pointer-to-Pointer

Let us see how to change the pointer in the function using a ptr-to-ptr parameter

  • ppInt:it is is the ptr-to-ptr. We will never transform this as if we do.
  • *ppInt:itis the pointed pointer. If we improve this, we are varying the contents of the pointed pointer, which is an address and in the above example, pvar. In other words, we are effectivelytransforming what pvar points to.
  • **ppInt is the dereferenced twice variable which is what pvar points to.

Passing pointers to functions

the arguments are passed to functions by value. The varying the value of a variable in a function does not generally change its value in the calling function. Consider the following example :

Here the parent() function primes the integer variable n1 to 0. The value of n1 is then delivered to fn(). After entering the function, nArg is equal to 0, the value passed. fn() alters the value of nArg to 10 before returning to parent(). Upon returning to parent(), the value of n1 is yet 0.

This is because that C++ doesn’t pass a variable to a function. In its place, C++ passes the value confined in the variable at the time of the call. That is, the expression is calculated, even if it is just a variable name, and the result is passed.

PASSING POINTER VALUES IN C++

Like any other basic type, a pointer may be passed as an argument to a function:

In this case, the address of n is handed to the function fn() rather than the value of n. The consequence of this difference is ostensible when you consider the assignment within fn().

Assume n is located at address 0x100. Fairly than the value 10, the call fn(&n) passes the value 0x100. In fn(), the assignment *pnArg = 10 stores the value 10 in the int variable situated at location 0x100, thus overwriting the value 0. Upon returning to parent(), the value of n is 10 since n is just one more name for 0x100.

PASSING BY REFERENCE IN C++

C++ delivers a shorthand for passing arguments by address — a shorthand that allows you to escape having to bother with pointers. The declarationcreates a variable n1 and a second reference to the identical n1 but with a new name, nRef:

int n1;            // declare an int variable
int&nRef = n1;    // declare a second reference to n1

nRef = 1;          // now accessing the reference
                   // has the same effect as accessing n1;
                   // n1 is now equal to 1

A reference variable like nRef must be initialized when it is statedfor the reason that every ensuing time that its name is used, C++ will take up that you mean the variable that nRef refers to.

This is named passing by reference. The testimony int&rnArg declares rnArg to be aallusion to an integer argument. The fn() function stocks the value 10 into the int location referenced by rnArg.

 Return pointer on or after function

Syntax :

As an alternative of a regular value or else even a reference, a function can return a pointer. You can start to classify this by typing the * operator on the left side of the function’s name.as like this,

double * GetSalary()

{

 

}

Then, use the body of the function to describe it. Before the closing curly bracket of the function, think of to return a pointer to the return value.

e.g.:

double * GetSalary()

{

double salary = 26.48;

double *HourlySalary = &salary;

returnHourlySalary;

}

Since a pointer by defining is a reference to the address where a variable lives, when a function is defined as returning a pointer, you can also return a reference to the appropriate type. Here is an example:

double * GetSalary()

{

double salary = 26.48;

return&salary;

}

After defining the function, you can call it. Think of that the asterisk is used to get the value of a pointer. This means that, when calling the function, if you need to access its value, make sure you take in the asterisk on the left side of the name of the function.

 Difference between C++ Reference and C++Pointer

POINTER

  1. Its not compulsory to reset the pointer at the time of declaration. Like

Code:

int a = 10;

int *P = &a; //It is not necessary

Another way is :

Code:

int a  = 10;

int *P;

P =  &a;

  1. You can create the array of Pointer.
  2. You can assign NULL to the pointer like

Code:

int *P = NULL; //Valid

  1. You can use pointer to pointer.

REFERENCE

Itsessential to make ready the Reference at the time of declaration. Like

Code:

int&a = 10;

int&a;   //Error here but not in case of Pointer.

  1. You can not create the Array of reference.
  2. You can not assign NULL to the reference like

Code:

int&a = NULL; //Error

  1. You can not use reference to reference.
  1. Pointers and referencesseemdissimilar enough as pointers use the * and -> operators, references use ,however they seem to do similar things. Both pointers and references let you refer to other objects indirectly.
  2. First, distinguish that there is no such thing as a null reference. A reference must always refer to some object. if you have a variable whose persistence is to refer to another object, but it is conceivable that there might not be an object to refer to, you should make the variable a pointer, since then you can set it to null. if the variable must continuously refer to an object, i.e., if your strategy does not let for the possibility that the variable is null, you should perhaps make the variable a reference.
    “But wait,” you wonder, “what about underhandedness like this?”
char *pc = 0;          // set pointer to null  
char&rc = *pc;        // make reference refer to                         
                       // dereferenced null pointer  

7.
Well, this is evil, pure and simple. The results are undecided (compilers can produce output to do whatever thing they like), and people who write this kind of code should be shunned until they agree to cease and desist. If you have to anxiety about things like this in your software, you’re maybe best off escaping references completely. One otherwise the other that or presiding a better class of programmers to work with. We’ll from this timeoverlook the prospect that a reference can be null.
For the reason that a reference must refer to an object, C++ requires that references be initialized:

string&rs;             // error! References must  
                        // be initialized  
string s("xyzzy");  
string&rs = s;         // okay, rs refers to s   

8.
Pointers are subject to no such restriction:

string *ps;             // uninitialized pointer:  
                        // valid but risky  	

9.
The circumstance that there is no such thing as a null reference suggests that it can be more well-organized to use references than to use pointers. That’s because there’s no necessity to test the soundness of a reference before using it:

void printDouble(const double&rd)  
{  
    cout <<rd;         // no need to test rd; it  
}                       // must refer to a double 

10.
the Pointers, on the other hand, should usually be verified against null:

void printDouble(const double *pd)  
{  
if (pd) {             // check for null pointer  
cout << *pd;  
}  
}  	

11.
One moresignificant difference between pointers and references is that pointers may be recast to refer to different objects. A reference, still, always denotes to the object with which it is initialized:

string s1("Nancy");  
string s2("Clancy");  
string&rs = s1;         // rs refers to s1  

string *ps = &s1;        // ps points to s1

rs = s2;                 // rs still refers to s1,  
                         // but s1's value is now  
                         // "Clancy"  

ps = &s2;                // ps now points to s2;  
                         // s1 is unchanged   	

12.
you should use a pointer each and every time you must to take into account the chance that there’s not anything to refer to or whenever you need to be able to refer to different things at different times (in which case you can change where the pointer points). You would use a reference at any time you know there will always be an object to refer to and you also see that once you’re referring to that object, you’ll never need to refer to everything else.
There is one other situation in which you should use a reference, and that’s when you’re implementing certain operators. The most common example is operator[]. This operator typically needs to return something that can be used as the target of an assignment:

vector v(10);       // create an int vector of size 10;  
                         // vector is a template in the  
                         // standard C++ library  
v[5] = 10;               // the target of this assignment is  
                         // the return value of operator[]   

13.
Uncertainty operator[] returned a pointer like this:
*v[5] = 10;
But this makes it look like v is a vector of pointers, which it’s not. For this purpose, you’ll nearlyeach time want operator[] to return a reference.
References, then, are the feature of optimal when you know you have rather to refer to, when you’ll never need to refer to anything else, and when applying operators whose syntactic necessities make the use of pointers uninvited. In all other cases, stick with pointers.

Advantages of Pointers s

1)it can return more then one value from a function
2)no necessity to pass the whole object to a function..can pass just the address
3)if we need our object to be adapt by some function then we have only option to pass its address or else reference
4)can implement run time polymorphism i.e.virtual…function
5)in writing driver …..pointer is desirable….also can do programming at low level
6)can implement garbage collection thing like reference calculating
7)if need to shere some object omng classes we can have the pointer of that object
in each intyerested classes

……actually we can’t move without pointer …..its power of c &c++s
Increasing the programming performance , Using pointers we can able to access the variables faster
* Dynamic memory management
* Data structure handling (Linkedlist, Stack ,Queue, Data dictionary,….)
* File management using FILE pointer
-Dangling pointers, mostly, create difficult to diagnose errors.
-Pointers lead to memory leaks.
– For parameter passing with reference, in C language using pointers were compulsory. C++ has new construct which is extremegreater.
– Majority of string handling operations depend on pointer to char.
– Pointers make developing/coding of certain Abstract Data Types (e.g. self referential structures) very simple.
– Searching/sorting of large size data is very efficient.
– Polymorphic behaviour of objects is possible only with pointers.

Leave A Comment

Your email address will not be published. Required fields are marked *