What is Pointer?
Pointers stores the address of variables or a memory location.
Syntax:
datatype *var_name;
e.g. int *ptr;
Above example states that:
//An example pointer “ptr” that holds
// address of an integer variable or holds
// address of a memory whose value(s) can
// be accessed as integer values through “ptr”
For Free Demo classes Call: 8237077325
Registration Link:Click Here!
We must understand the following operators to use pointers:
- i) Unary operator(&): It is used to that the address of that variable. e.g. &x -It gives the address of variable x.
- ii) Unary * (Asterisk): To declare a pointer variable, when a pointer variable is declared in C/C++, there must a * before its name.To access the value stored in the address we use the unary operator (*) that returns the value of the variable located at the address specified by its operand.
Pointer Arithmetic
Following arithmetic operations can be performed on pointers.
- i) incremented ( ++ )
A pointer is incremented by address. eg *ptr is pointed to location 1000 after ptr++, its value is 1002. Depends on compiler its address is varied by 2 bytes or 4-bytes.
- ii) decremented ( — ) Pointer is decremented by address.eg *ptr is pointed to location 1004 after ptr++, its value is 1002.
Array Name as Pointers:
The array name is work as an internal pointer which stores address of the first element of the array. It can be used interchangeably.
Why C treats array parameters as pointers?
Because it is less time consuming and more efficient. Though if we can pass the address of each element of the array to a function as an argument but it will be more time-consuming. So it’s better to pass the base address of the first element to the function
Double Pointer (Pointer to Pointer) in C:
We know that a pointer points to a location in memory and therefore it is used to store the address of variables. When we define a pointer to pointer. It means pointer stores the address of another pointer.
Declaration of pointer to pointer in C?
We have to place one more ‘*’ before the name of the pointer.
Syntax:
int **ptr; // declaring double pointers
For Free Demo classes Call: 8237077325
Registration Link:Click Here!
String using pointer:
In string the variable name of the string e.g. char str[], str holds the address of the first element of the array i.e., it points at the starting memory address.
We can create a character pointer ptr which store the address of the string str variable in it.
char *ptr = str;
In above example *ptr holds the address of first character of str.Accessing string via pointer
If we want to access and display the elements of the string we can use a loop and check for the \0 null character.
#include <stdio.h>
#include<conio.h>
void main() {
// string variable
char str[6] = “Hello”;
// pointer variable
char *ptr = str;
// print the string
while(*ptr != ‘\0’) {
printf(“%c”, *ptr);
// move the ptr to the next memory location
ptr++;
}
return 0;
}
Using the pointer to store string:
We can create a character pointer that points at a string value stored at some memory location.
In following example ,We are using character pointer variable strPtr to store string value.
#include <stdio.h>
#include<conio.h>
void main()
{
char *strPtr = “Hello”; // pointer variable to store string
char *t = strPtr;// temporary pointer variable
while(*t != ‘\0’)
{
printf(“%c”, *t); // print the string
t++; // increment the t pointer with next memory location
}
return 0;
}
For Free Demo classes Call: 8237077325
Registration Link:Click Here!
In the above program, we store “Hello” string in pointer variable, another pointer variable t which stores whatever address stores in stPtr.
What is a structure pointer?
We can have a pointer to a structure. In pointer to structure, members of structures are accessed using arrow ( -> ) operator.
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {1, 2};
// p2 is a pointer to structure p1
struct Point *p2 = &p1;
// Accessing structure members using structure pointer
printf(“%d %d”, p2->x, p2->y);
return 0;
}
Dangling pointer:
A dangling pointer has occurred where memory has been allocated dynamically for a variable and after using the memory is freed, but when the pointer is reused if it is still pointing to the previous location, then it is called as dangling pointer
Void Pointer:
This pointer points to the memory location, which doesn’t have any specific type. Void refers to the type. The type of data that pointer points to is can be any type. Suppose we assign the address of char data type to void pointer it will become char Pointer, and if int data type then int pointer and so on. Any pointer type is convertible to a void pointer. A void pointer can point any value.
Important Points:
i).void pointers cannot be dereferenced. It can be done by using typecasting the void pointer
ii)Pointer arithmetic is not possible on pointers of void due to lack of concrete value and thus size.
#include<stdlib.h>
int main()
{
int x = 4;
float y = 5.5;
void *ptr; //A void pointer
ptr = &x;
printf(“Integer value = %d\n”, *( (int*) ptr) ); // (int*)ptr – does type casting of void
// *((int*)ptr) dereferences the typecasted ptr = &y; // void pointer is now float
printf(“\nFloat value=%f”, *( (float*) ptr) );
return 0;
}
Null Pointer:
NULL Pointer is a pointer which is doesnot have nothing to point .If we don’t have address to be assigned to a pointer, then we can simply use NULL.
#include <stdio.h>
int main()
{
// Null Pointer
int *ptr = NULL;
printf(“The value of ptr is %u”, ptr);
return 0;
}
For Free Demo classes Call: 8237077325
Registration Link:Click Here!
Important Points:
i)NULL vs Uninitialized pointer – An uninitialized pointer stores an undefined value. A null pointer stores a defined value.
ii)NULL vs Void Pointer – Null pointer is a value, while void pointer is a type
Wild Pointer:
A pointer which doesnot have nothing to point not even NULL is known as
wild pointer.
#include<stdio.h>
#include<conio.h>
int main()
{
int *p; /* wild pointer */
int x = 10;
// p is not a wild pointer now
p = &x;
return 0;
}
What are near, far and huge pointers?
These are old pointer concepts which is used in 16-bit intel architectures not much use anymore.
Near pointer: This pointer is used to store 16-bit addresses within the segment. We can only access the 64kb of data at a time.
Far pointer: This pointer is used to store 32-bit address that can access memory outside the current segment. If to use this, the compiler allocates a segment register to store segment address and then register for storing offset within the current segment.
Huge pointer: This pointer is also used to store 32-bit address and can access outside segment as like far pointers, but in case of far-pointer, a segment is fixed. Whereas far pointer, the segment part cannot be modified, but in Huge pointer, it can be modified.
What is a memory?
Memory is nothing but where we store data that should be processed by the Processor. But this does not mean that it is a single component. It is a collection of several components.
Main-Memory is nothing but RAM stands for Random Access Memory. It needs electrical power in order to maintain the information. So, we called it as a Volatile-Memory.
For Free Demo classes Call: 8237077325
Registration Link:Click Here!
What is Dynamic Memory Allocation:
The memory allocated to the program could be divided into four categories.
- Code (compiled version of the program)
- Stack (which handles the function calls)
- Data (which keeps the variables)
- Heap
As we know that variable plays an important role in programming. And allocating memory to variables should be handled by the programmer.
There are three types of memory allocation techniques
- Static Memory Allocation
- Automatic Memory Allocation
- Dynamic Memory Allocation
Static Memory Allocation is nothing but when we declare a variable and each variable has a fixed size and memory is allocated at the starting point of the program and it gets free after the program finished its’ execution.
Automatic Memory Allocation means memory is allocated when a local variable which is declared in a compound statement, it gets memory when program control enters into a compound statement and get free when the program exists that compound statement.
Dynamic Memory Allocation: As we know that in Static Memory Allocation and Automatic Memory Allocation where we know the scope and memory size of the variable before the run time, but sometimes we need to identify the scope and memory size of a variable during run time.
For example, Let’s think that we want to allocate memory for a user_input which we don’t have to put a limit. As we don’t know how much memory the user_input needs it, in that case, we use Dynamic Memory Allocation. It means memory is allocated during run time. Let’s see another example to understand better.
As we know that C is a structured language, it has some fixed rules for programming. One of them is changing the size of an array. An array is a collection of the same type of data which stored at contiguous memory locations.
From the above figure, it can be seen that the size of the array is 9.Incase what if we want to change the size of the array then what is a requirement to change this size.
For Example, we want to add or insert 5 elements in an array where only 5 elements are needed to be entered in this array. In this case, the remaining 4 indices are just wasting memory in this array. So there is a requirement to lessen the length (size) of the array from 9 to 5.
Let us see another situation. In this situation, there is an array of 9 elements with all 9 indices filled. But there is a need to enter 3 more elements in this array. In this case, 3 indices more are required. So the size of the array needs to be changed from 9 to 12.
This procedure is called as Dynamic Memory Allocation.
Therefore, Dynamic Memory Allocation can be defined as the size of a data structure (like Array) is changed during the runtime or else we can also say that memory is allocated during run time.
C provides some functions to achieve these tasks. There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are:
- malloc()
- calloc()
- free()
- realloc()
1) malloc():
malloc() means memory allocation which is used to dynamically allocate a single large block of memory with the specified size. This returns a pointer of type void which means a pointer of any type.
Syntax:
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(100 * sizeof(int));
Suppose, here the size of int is of 4 bytes, the above statement states that it will allocate 400 bytes of memory. the pointer ptr which holds the address of the first byte in the allocated memory.
2) calloc():
calloc() means contiguous or continuous allocation function which is used to dynamically allocate the specified number of blocks of memory of the specified type. It initializes each block with a default value 0.
Syntax:
ptr = (cast-type*)calloc(n, element-size);
For Example:
ptr = (float*) calloc(25, sizeof(float));
As per the above statement, it allocates contiguous space in memory for 25 elements each with the size of the float.
3.) free():
free() function is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() are not de-allocated by their own. Therefore the free() function is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.
Syntax:
free(ptr);
4.) realloc():
realloc() or re-allocation function which is used to dynamically change the memory allocation of a previously allocated memory. It is also used where the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.
Syntax:
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size.
How does free() get to know the size of memory to be deallocated?
Consider the following example, a prototype of free() function which is used to free the memory allocated using malloc() or calloc() or realloc().
void free(void *ptr);
We have to note that the free function does not accept size as a parameter. Then question is that, How does free() function know how much memory to free by given just a pointer?
There is the most common way to store the size of memory so that free() knows the size of memory to be deallocated.
When memory allocation is done, the amount of heap space actually allocated is one word larger than the requested memory. The additional word is used to hold the size of the allocation which later used by free().
For Free Demo classes Call: 8237077325
Registration Link:Click Here!
Why pointer concept did not use in java?
Some reasons for Java does not support Pointers:
It would be impossible for the Virtual Machine to ensure that code containing pointer is safe without runtime checks.
Supporting pointer in Java is not more secure because they point to a memory location or used for memory management that loses the security as we use them directly.
We can use pointers to manually and allocate blocks of memory which is useful for applications like gaming applications, device drivers, etc. but for Object-Oriented programming. Instead of that Java provides Garbage Collection which takes care of memory management.
Advantages of Pointers:
- Pointers provide direct access to memory
- Pointers provide a way to return more than one value to the functions
- Reduces the storage space and complexity of the program
- Reduces the execution time of the program
- Provides an alternate way to access array elements
- Pointers can be used to pass information back and forth between the calling function and called function.
- Pointers allows us to perform dynamic memory allocation and deallocation.
- Pointers helps us to build complex data structures like a linked list, stack, queues, trees, graphs, etc.
- Pointers allows us to resize the dynamically allocated memory block.
- Addresses of objects can be extracted using pointers
Drawbacks of pointers in c:
- Uninitialized pointers might cause a segmentation fault.
- The dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to a memory leak.
- Pointers are slower than normal variables.
- Memory corruption has occurred if pointers are updated with incorrect values. Memory corruption creates many problems. It can set unpredictable values to next memory elements; it can set invalid pointer values; and worst of all, it can corrupt dynamic memory allocator thus causing crash/core-dump of the application/process.
For Free Demo classes Call: 8237077325
Registration Link:Click Here!
Call the Trainer and Book your free demo Class now!!!
© Copyright 2019 | Sevenmentor Pvt Ltd.