Wednesday, January 4, 2017

Pass by reference using Pointer and Dynamic memory allocation


Pass by reference using Pointer :

#include<iostream>

using namespace std;

 void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int x=2,y=3;
cout<<"Before swap: "<<endl; cout<<x<<" "<<y<<endl;
swap(&x,&y);
cout<<"After swap: "<<endl;
cout<<x<<" "<<y;
return 0;
}

Output:
 Before swap: 2 3
After swap:
3 2

Here, int * a= &x; it means that *a =x i.e. *a=2 and similarly *b=3. After swap *a=3 and *b =2 this means also x=3 and y=2.

Dynamic memory allocation using new and delete operator:

How does dynamic memory allocation work?

Your computer has memory (probably lots of it) that is available for applications to use. When you run an application, your operating system loads the application into some of that memory. This memory used by your application is divided into different areas, each of which serves a different purpose. One area contains your code. Another area is used for normal operations (keeping track of which functions were called, creating and destroying global and local variables, etc…). We’ll talk more about those later. However, much of the memory available just sits there, waiting to be handed out to programs that request it.
When you dynamically allocate memory, you’re asking the operating system to reserve some of that memory for your program’s use. If it can fulfill this request, it will return the address of that memory to your application. From that point forward, your application can use this memory as it wishes. When your application is done with the memory, it can return the memory back to the operating system to be given to another program.
Unlike static or automatic memory, the program itself is responsible for requesting and disposing of dynamically allocated memory.

#include <iostream>
 int main()
{
int *ptr = new int; // dynamically allocate an integer
*ptr = 7; // put a value in that memory location
delete ptr; // return the memory to the operating system. ptr is now a d angling pointer.

ptr =0; //ptr is now a nullptr
return 0;

}

No comments:

Post a Comment