Monday, February 19, 2024

POINTERS IN C++

 Pointers in C++

  • HOW TO USE A POINTER
  • APPLICATION OF C++ POINTER
  • ADVANTAGE AND DISADVANTAGE
  • USAGE OF POINTER
  • WHAT ARE POINTERS AND STRING LATERALS
  • WHAT IS NULL POINTER
  • WHAT IS AN INVALID POINTER
  • REFERENCES IN C++
  • POINTER VS REFERENCES

A pointer in C++ is a variable, also known as a locator or pointer, that points to the address of a value.

The address symbol is represented by a cursor. In addition to creating and modifying dynamic data structures, they allow programs to copy speech by reference. One of the main uses of pointers is to iterate over the components of arrays or other data structures. A pointer variable that refers to the same data type as the variable you are manipulating is set to the address of that variable (e.g., int or string).

Syntax

  1. datatype *var_name;   
  2. int *ptr;   // ptr can point to an address which holds int data

 

How to use a pointer

Define a pointer variable., which uses the address of a variable, a pointer to the address of the variable, and the unary operator (&) to give the address.

Using the unary operator (*), which returns the value of a variable’s value at the address given by this argument, accesses the value stored at the address.

Since the data type knows how many bytes of data to store, we bind it by reference. The size of the data type to which the cursor is added when the cursor is incremented.

 Application of C++ pointer

The following are implementations of pointers in C++:

Passing arguments by reference: Passing by reference serves two purposes

·   Accessing array elements: The compiler internally uses references to access array elements.

·   Return multiple values: for example, returning the square and square root of numbers.

·  Dynamic Memory Allocation: We can use pointers to dynamically allocate memory. The advantage of dynamically allocated memory is that it is not deleted until we delete it individually.

·   Implementation of data structures.

·   System-level programming where memory addresses are useful.

 Advantage of pointer

A pointer reduces code and improves performance, is used to get strings, trees, etc., and is used with arrays, structures, and functions.

·    We can return multiple values ​​from a function using a pointer.

·    Allows to use the memory location of any computer and memory.

 

Disadvantage

   Complexity

·       Risk of errors

·       Memory leaks

·       Dangling pointer

·       Uninitialized pointer

 

Usage of pointers

1)  Dynamic memory allocation

In C, we can dynamically allocate memory with malloc() and calloc() functions where a pointer is used.

2) Arrays, Functions, and Structures in language references are widely used in arrays, functions, and structures. This reduces code and improves performance.

Let us try an example of the pointer in C++

#include <iostream>

using namespace std;

int main()

{

              int x = 10; // variable declared

              int* myptr; // pointer variable

              // storing address of x in pointer myptr

              myptr = &x;

              cout << "Value of x is: ";

            cout << x << endl;

              // print the address stored in myptr pointer variable

              cout << "Address stored in myptr is: ";

              cout << myptr << endl;

              // printing value of x using pointer myptr

              cout << "Value of x using *myptr is: ";

              cout << *myptr << endl;

              return 0;

}

Output

Value of x is: 10

Address stored in myptr is: 0x7ffd2b32c7f4

Value of x using *myptr is: 10

Explanation.

The above program declares an integer variable 'x' with an initial value of 10 and a pointer variable called 'myptr'. The memory address of X is assigned to 'myptr'. It then prints the value of x, the address stored in myptr, and the value of x obtained by dereferencing the pointer to myptr.

 Let us try another C++ program to swap the number without using the 3rd variable

 

#include <iostream>  

using namespace std;  

int main()  

{  

int a=20,b=10,p1=&a,p2=&b;    

cout<<"Before swap: p1="<<p1<<" p2="<<p2<<endl;    

p1=p1+p2;    

p2=p1-p2;    

p1=p1-p2;    

cout<<"After swap: p1="<<p1<<" p2="<<p2<<endl;    

   return 0;  

}  

Output

 

Before swap: ∗p1=20 ∗p2=10
After swap: ∗p1=10 ∗p2=20

 

What are pointers and string literals?

String literals are null-terminated strings. The elements of a string literal are arrays of type const char (because characters in a string cannot be changed) plus a final null character.

What is a null pointer?

This unique pointer type available in C++ represents a missing type. Pointers that point to a value that has no type are called empty pointers (and thus also have undefined length and undefined dereference properties). This shows that void pointers are very flexible because they can point to any data type. This flexibility has its advantages.

Direct dereference is not possible with these pointers. Before they can be referenced, they must be converted to another pointer that points to a specific data type.

 What is an invalid pointer?

A pointer must point to a valid address, not necessarily useful objects (like arrays). We call these invalid pointers. Also, invalid pointers are uninitialized pointers.

  1. int *ptr1;  
  2. int arr[10];  
  3. int *ptr2 = arr+20; 

Here ptr1 is uninitialized making it invalid and ptr2 is out of bounds of arr making it invalid as well. (Note that not all build errors are due to bad references.).

 

What is a null pointer?

 A null pointer is not just an incorrect address; it also indicates nothing. There are two ways to mark a pointer as NULL.

  1. int *ptr1 = 0;  
  2. int *ptr2 = NULL; 

 What is a pointer to a pointer?

In C++, we can construct a pointer to another pointer, which can then point to data or another pointer. The one-word operator (*) is all that is needed in the syntax to declare a pointer to each level of indirectness.

 

char a;

char *b;

char ** c;

a = 'g';

b = &a;

c = &b;

 

References in C++

When a variable is declared as a reference, it becomes an alternative name for an existing variable. A variable can be declared as a reference by placing the "and" statement. There are three ways to pass arguments to a C++ function:

    call-by-value

·       call-by-reference with a pointer argument

·       call-by-reference with a reference argument.

 Let us try out all these three in a C++ program with their output

 

#include   

using namespace std;  

// Pass-by-Value  

int square1(int n)  

{

cout << "address of n1 in square1(): " << &n << "\n";  

n *= n;  

return n;  

}  

// Pass-by-Reference with Pointer Arguments  

void square2(int* n)  

{  

cout << "address of n2 in square2(): " << n << "\n";  

*n *= *n;  

}  

// Pass-by-Reference with Reference Arguments  

void square3(int& n)  

{  

      

cout << "address of n3 in square3(): " << &n << "\n";  

n *= n;  

}  

void example()  

{  

    // Call-by-Value  

    int n1 = 8;  

    cout << "address of n1 in main(): " << &n1 << "\n";  

    cout << "Square of n1: " << square1(n1) << "\n";  

    cout << "No change in n1: " << n1 << "\n";  

  

    // Call-by-Reference with Pointer Arguments  

    int n2 = 8;  

    cout << "address of n2 in main(): " << &n2 << "\n";  

    square2(&n2);  

    cout << "Square of n2: " << n2 << "\n";  

    cout << "Change reflected in n2: " << n2 << "\n";  

  

    // Call-by-Reference with Reference Arguments  

    int n3 = 8;  

    cout << "address of n3 in main(): " << &n3 << "\n";  

    square3(n3);  

    cout << "Square of n3: " << n3 << "\n";  

    cout << "Change reflected in n3: " << n3 << "\n";  

}  

// Driver program  

int main() { example(); }  

Output

address of n1 in main(): 0x7fffa7e2de64

address of n1 in square1(): 0x7fffa7e2de4c

Square of n1: 64

No change in n1: 8

address of n2 in main(): 0x7fffa7e2de68

address of n2 in square2(): 0x7fffa7e2de68

Square of n2: 64

Change reflected in n2: 64

address of n3 in main(): 0x7fffa7e2de6c

address of n3 in square3(): 0x7fffa7e2de6c

Square of n3: 64

Change reflected in n3: 64

 

Pointer Vs References

This presents the differences between referrals and referrals. Both dereferences and dereferences can be used to modify the local variables of a function within another function. Both can also be used to preserve copying of large objects when they are passed as arguments to functions or returned from functions for efficiency.

Despite the above similarities, there are the following differences between pointers and pointers.

 References are less efficient than references

Once a reference is created, you cannot later make a reference to another object; it cannot be reset. This is often done with pointers.

References cannot be NULL values. Pointers are often converted to NULL to indicate that they do not point to anything valid.

 Reference must be justified in the declaration. Pointers have no such limitation.

Pointer Control Vs Reference Control in C++: In C++ we can pass parameters to a function either through pointers or through references. In both cases, we get the same result.

So what to prefer and why?

 Passing a pointer reference in C++: In this article, we compare the uses of "pointer to pointer" and "reference to pointer" in some cases.

For example, we can consider it as

 

int a = 10;

void*aa = &a;. //it is valid

void &ar = a; // it is not valid

No comments:

Post a Comment

Featured Post

ASSOCIATION RULE IN MACHINE LEARNING/PYTHON/ARTIFICIAL INTELLIGENCE

Association rule   Rule Evaluation Metrics Applications of Association Rule Learning Advantages of Association Rule Mining Disadvantages of ...

Popular