COURSE TITLE: SOFTWARE DEVELOPMENT VI
COURSE CODE: VIT 351
TOPICS COVERED:
INTRODUCTION TO POINTERS
TYPES OF POINTERS
POINTERS EXAMPLES
POINTERS ARITHMETICS
ADVANTAGES AND DISADVANTAGES OF POINTERS
STATIC MEMORY ALLOCATION
DYNAMIC MEMORY ALLOCATION
QUIZ SET 3
NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...
VIT351 Software Development VI Unit3
1. D.E.I. TECHNICAL COLLEGE
COURSE TITLE: Software Development-VI
SLIDE-3
COURSE CODE: VIT351
CLASS: DIPLOMA IN INFORMATION TECHNOLOGY VOCATIONAL (1ST YEAR)
SESSION: 2019-20
2. TOPICS COVERED
INTRODUCTION TO POINTERS
TYPES OF POINTERS
POINTER ARITHMETICS
DYNAMIC MEMORY ALLOCATION
QUIZ SET 3
3. INTRODUCTION TO POINTER:
A pointer is a variable which is capable of storing the address of a variable.
They provide the means through which memory location of a variable can be directly
accessed.
data_Type *pointer_name;
Example:
int *ip // pointer to integer variable
float *fp; // pointer to float variable
double *dp; // pointer to double variable
char *cp; // pointer to char variable
Whatever would be the address of our variable following things are important:
Addresses are always in the range 0 to 4294967295. ( Target Platform dependent)
Every byte will have some address number
Address number is always an integer, even if the variable is not of type int.
We cannot decide address number of any variable.
Addresses are also known as references.
GO TO TOPICS
4. ‘&’ Ampersand or reference Operator
& is called address of operator, also known as referencing operator.
It is a unary operator, thus requires only one operand.
Operand must be a variable.
& returns the reference number of variable specified as the operand.
#include<stdio.h>
int main()
{
int var = 10;
printf("Value of the variable var is: %dn", var);
printf("Memory address of the variable var is: %xn", &var);
return 0;
}
5. ‘*’ Star Operator:
Indirection operator is also known as ‘value at’ operator or ‘dereferencing operator’.
It is also a unary operator that is single operand is needed.
Operand must be a variable address.
It gives a representation to the block whose address is specified in the operand.
#include<stdio.h>
int main(){
int number=10;
int *p;
p=&number; //stores the address of number variable
printf("Address of p variable is %x n",p);
// p contains the address of the number therefore printing p gives the address of number.
printf("Value of p variable is %d n",*p);
// As we know that * is used to dereference a pointer therefore if we print *p, we will get the value
stored at the address contained by p.
return 0;
}
6. Example:
#include <stdio.h>
int main () {
int i = 20; // actual variable declaration
int *iptr; // pointer variable declaration
iptr = &i; // store address of i in pointer variable
int j = *iptr; // store variable stored in location pointed by iptr* in j
/* address stored in pointer variable */
printf("Address stored in ip variable: %xn", iptr );
/* access the value using the pointer */
printf("Value of *ip variable: %dn", j );
return 0;
}
7. Points to Remember
1. While declaring/initializing the pointer variable, * indicates that
the variable is a pointer.
2. The address of any variable is given by preceding the variable
name with Ampersand &.
3. The pointer variable stores the address of a variable. The
declaration int *a doesn't mean that a is going to contain an
integer value. It means that a is going to contain the address of a
variable storing integer value.
4. To access the value of a certain address stored by a pointer
variable, * is used. Here, the * can be read as 'value at'.
8. Common mistakes when working with Pointers
Suppose, you want pointer pc to
point to the address of c. Then,
int c, *pc;
// pc is address but c is not
pc = c; // Error
// &c is address but *pc is not
*pc = &c; // Error
// both &c and pc are addresses
pc = &c;
// both c and *pc values
*pc = c;
Why didn't we get an error when using int *p = &c;?
It's because
int *p = &c;
is equivalent to
int *p:
p = &c;
In both cases, we are creating a pointer p (not *p)
and assigning &c to it.
To avoid this confusion, we can use the statement like
this:
int* p = &c;
9. Types of Pointers
There are several types of pointers which differ based on the way they are used in a
program.
Null Pointer
A null value is assigned to a pointer when you are not sure what address is to be assigned. It
can be done by assigning ‘NULL’ value to a pointer at the time of declaration. The value of
this pointer is 0.
int *ptr = NULL;
#include <stdio.h>
int main()
{
int *p = NULL; //null pointer
printf(“The value inside variable p is:n%x”,p);
return 0;
}
GO TO TOPICS
10. Wild Pointer
A wild pointer is created by not assigning
any value to a pointer variable. It should be
used carefully as it may result in
unexpected results.
#include <stdio.h>
int main()
{
int *p; //wild pointer
printf("n%d",*p);
return 0;
}
Dangling Pointer
When a pointer points to a deleted
variable or de-allocated memory the
pointer is known as a dangling pointer. This
pointer points at a non-existing memory
location.
#include <stdio.h>
int main()
{
int *p;
{
int x=4;
p=&x;
}
*p=5;
return(0);
}
11. void Pointer
In C programming, a void pointer is also called as a generic pointer.
It does not have any standard data type. A void pointer is created by using the keyword
void.
It can be used to store an address of any variable.
#include <stdio.h>
int main()
{
void *p = NULL; //void pointer
printf("The size of pointer is:%dn",sizeof(p));
return 0;
}
12. Pointer to Pointer (Double Pointer)
Pointers are used to store the address of other variables of similar datatype.
But if you want to store the address of a pointer variable, then you again
need a pointer to store it.
Thus, when one pointer variable stores the address of another pointer
variable, it is known as Pointer to Pointer variable or Double Pointer.
Syntax:
int **p1;
13. Example
#include <stdio.h>
int main() {
int a = 10;
int *p1; //this can store the address of variable a
int **p2;
/*
this can store the address of pointer variable p1 only.
It cannot store the address of variable 'a'
*/
p1 = &a;
p2 = &p1;
printf("Address of a = %un", &a);
printf("Address of p1 = %un", &p1);
printf("Address of p2 = %unn", &p2);
// below print statement will give the address of 'a‘
printf("Value at the address stored by p2 = %un",
*p2);
printf("Value at the address stored by p1 = %dnn",
*p1);
printf("Value of **p2 = %dn", **p2); //read this *(*p2)
/*
This is not allowed, it will give a
compile time error-
p2 = &a;
printf("%u", p2);
*/
return 0;
}
14. Pointer Arithmetic
Rule 1: Take care for the compatibility
Example
int main()
{
int i=3;
char *j;
j = &i; //wrong as incompatible assignment
printf(“%d %u”, i, &i);
}
(Error message depends on compiler most of the C compilers do not show any error)
GO TO TOPICS
15. Rule 2: We cannot add two addresses.
Example
int main()
{
int *k, i=3, *j;
j = &i;
k = j + j;
printf(“%d”, k);
return(0);
}
Error: Invalid pointer addition.
Similarly, we cannot multiply, divide two addresses.
16. Rule 3: We cannot multiply scalar value to an address. Similarly we cannot
divide an address with scalar value
int main()
{
int *k, i=3, *j;
j = &i;
k = j * 5; //Error, cannot multiply address and scalar value
printf(“%d”, k);
return(0);
}
17. Rule 4: Adding 1 to the pointer gives address of the immediately next block of
the same type. Similarly subtracting 1 from the pointer gives address of the
previous block of the same type
int main()
{
int *k, i=3, *j; //assume address of i is 1000
j = &i; // the value stored in j is 1000
k = j + 1; // j+1 is adding 1 to the address stored in j that is 1000, the result is 1004
printf(“%d”, k); //Output is 1004
return(0);
}
18. Advantages of Pointer
Pointers are useful for accessing memory locations.
Pointers provide an efficient way for accessing the elements of
an array structure.
Pointers are used for dynamic memory allocation as well as
deallocation.
Pointers are used to form complex data structures such as
linked list, graph, tree, etc.
19. Disadvantages of Pointer
Pointers are a little complex to understand.
Pointers can lead to various errors such as segmentation faults
or can access a memory location which is not required at all.
If an incorrect value is provided to a pointer, it may cause
memory corruption.
Pointers are also responsible for memory leakage.
Pointers are comparatively slower than that of the variables.
Programmers find it very difficult to work with the pointers;
therefore it is programmer's responsibility to manipulate a
pointer carefully.
21. Memory Allocation Process
Memory Allocation is a process by which computer programs and services are
assigned with physical or virtual memory spaces.
Global variables, static variables and program instructions get their memory in
permanent storage area whereas local variables are stored in a memory area called
Stack.
The memory space between these two region is known as Heap area. This region is
used for dynamic memory allocation during execution of the program.
The size of heap keep changing.
22. DYNAMIC MEMORY ALLOCATION
Dynamic memory allocation is the process of assigning the
memory space during the execution time or the run time.
Library routines known as memory management functions are
used for allocating and freeing memory during execution of a
program. These functions are defined in stdlib.h header file.
The mechanism by which storage/memory/cells can be
allocated to variables during the run time is called Dynamic
Memory Allocation.
23. Difference between SMA & DMA
Static Memory Allocation Dynamic Memory Allocation
In this case, variables get allocated
permanently
In this case, variables get allocated only if
your program unit gets active
Allocation is done before program
execution
Allocation is done during program
execution
It uses the data structure called stack for
implementing static allocation
It uses the data structure called heap for
implementing dynamic allocation
Less efficient More efficient
There is no memory reusability There is memory reusability and memory
can be freed when not required
24. malloc() Function
The malloc() function allocates a block of memory in bytes.
The malloc() function is like a request to the RAM of the system to
allocate memory, if the request is granted, returns a pointer to
the first block.
However if it fails to allocate memory returns NULL.
The malloc() function reserves a block of memory of specified
size and returns a pointer of type void.
ptr=(cast type*)malloc(byte size);
25. Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using
malloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
26. calloc() Function
The calloc() function is used for requesting memory space at run
time for storing derived data types such as arrays and structures.
While malloc() allocates a single block of storage space, calloc()
allocates multiple blocks of storage, each of same size, and then
sets all bytes to zero.
ptr = (cast type*)calloc(n, element size);
This statement allocates contiguous space for n blocks each of size
element size bytes. All bytes are initialized to zero and pointer to
the first byte of the allocated region is returned.
If not enough space NULL is returned.
27. Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by calloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using
calloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
28. realloc() Function
Using the realloc() function, you can add more memory size to
already allocated memory.
It expands the current block while leaving the original content as
it is. realloc stands for reallocation of memory.
realloc can also be used to reduce the size of the previously
allocated memory.
ptr = realloc (ptr,newsize);
The free function is used to de-allocate the previously
allocated memory using malloc or calloc functions.
free(ptr);
free() Function
29. Example#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
30. Continue…
// Get the new size for the array
n = 10;
printf("nnEnter the new size of the array: %dn", n);
// Dynamically re-allocate memory using realloc()
ptr = realloc(ptr, n * sizeof(int));
// Memory has been successfully allocated
printf("Memory successfully re-allocated using realloc.n");
// Get the new elements of the array
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}
31. Difference between malloc() & calloc()
malloc() calloc()
It allocates only single block of requested memory It allocates multiple blocks of requested memory
int *ptr;
ptr = malloc( 20 * sizeof(int) );
For the above, 20*4 bytes of memory only allocated in
one block.
Total = 80 bytes
int *ptr;
ptr = calloc( 20, 20 * sizeof(int) );
For the above, 20 blocks of memory will be created
and each contains 20*4 bytes of memory.
Total = 1600 bytes
No. of Argument =1 No. of Argument=2
malloc () doesn’t initializes the allocated memory.
It contains garbage values
calloc () initializes the allocated memory to zero
type cast must be done since this function returns void
pointer int *ptr;
ptr = (int*)malloc(sizeof(int)*20 );
Same as malloc () function
int *ptr;
ptr = (int*)calloc( 20, 20 * sizeof(int) );
Return a pointer to the starting address of the
allocated memory or Return NULL
Return a pointer to the starting address of the
allocated memory or Return NULL
32. Advantages of DMA
1. When we do not know how much amount of memory would be needed for
the program beforehand.
2. When we want data structures without any upper limit of memory space.
3. When you want to use your memory space more efficiently. Example: If you
have allocated memory space for a 1D array as array[20] and you end up
using only 10 memory spaces then the remaining 10 memory spaces would
be wasted and this wasted memory cannot even be utilized by other
program variables.
4. Dynamically created lists insertions and deletions can be done very easily just
by the manipulation of addresses whereas in case of statically allocated
memory insertions and deletions lead to more movements and wastage of
memory.
5. When you want you to use the concept of structures and linked list in
programming, dynamic memory allocation is a must.
33. 2. Let’s assume x is an integer variable. What does &x imply?
A. 21
B. 23
C. 32
D. 18
1. What will be the output?
A. Value contained in x
B. Absolute memory address of x
C. x is a pointer variable
D. None of above
int x=21;
int *p= &x;
printf(“%d”, *p+11);
GO TO TOPICS
34. 4. What is the role of sizeof() function in case of dynamic
allocation?
A. malloc()
B. free()
C. new()
D. None of the above
3. Which of the below functions is used for dynamic
allocation of memory in c language
A. sizeof() is used to determining the datatype
B. Use of sizeof() function has no use when allocating memory
dynamically
C. Use of sizeof() function is optional
D. Sizeof() is used for determining the size of a datatype or a
variable in terms of bytes
35. 6. In the prototype given below. The parameters
used are int * fun(int *x, int y)
A. Value contained in p
B. Value contained in address(reference) stored in p.
C. Address(reference) of p.
D. Address of the variable stored in p.
5. Assuming p is declared as a pointer variable. What
is the meaning of *p?
A. Both x and y are pointer type
B. Only x is pointer type
C. Only y is pointer type
D. No pointers are used
36. 8. In a function call by reference we have to use a pointer type
variable as parameter. Is the statement correct?
A. The statement will generate runtime error
B. The statement will generate compiler error
C. Integer without pointer
D. Integer Pointer
7. In the prototype given below. The return type is a
int * fun(int *x, int y)
A. No, we can use reference variable also (a reference
variable uses & prefix with a variable name)
B. Yes, it always needs to be a pointer
C. The question is irrelevant
D. Not sure