Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore E-LESSON-6

E-LESSON-6

Published by Teamlease Edtech Ltd (Amita Chitroda), 2020-10-24 03:28:47

Description: E-LESSON-6

Search

Read the Text Version

IDOL Institute of Distance and Online Learning ENHANCE YOUR QUALIFICATION, ADVANCE YOUR CAREER.

BCA 2 All right are reserved with CU-IDOL Computer Programming Course Code: BCA 112 Semester: First SLM Unit: e-Lesson No.: 8 6 www.cuidol.in Unit- 8(BCA112)

Pointers and 33 DMA OBJECTIVES INTRODUCTION • Describe the concepts of pointers In this session we are going to learn about • The concepts of pointers • Elaborate the pointer to pointer concept • The concepts of pointer to pointer • Difference between pointer to array and array of • Differentiate between pointer to array and array of pointers pointers • Functions returning a pointer • Describe functions returning a pointer • The concepts of dynamic memory allocation • The use of malloc and calloc functions • Describe the concepts of dynamic memory • Difference between malloc and calloc functions allocation • The use of realloc and free functions • Demonstrate the use of malloc and calloc functions • Differentiate between malloc and calloc functions • Illustrate the use of realloc and free functions www.cuidol.in Unit- 8(BCA112) AINllSTrIiTgUhTt EarOeFrDesISeTrAvNedCEwAitNhDCOUN-ILDINOEL LEARNING

TOPICS TO BE COVERED 43 • Concepts of Pointers INTRODUCTION • Null Pointer • Pointer Arithmetic • Pointers and Arrays • Array of Pointers • Pointers and Function • Basics of Dynamic Memory Allocation • Dynamic Memory Allocation Functions www.cuidol.in Unit- 8(BCA112) INASlTl ITriUgThEt OarFeDrIeSsTeArNvCeEd AwNitDh OCNUL-IIDNOE LLEARNING

Concepts of Pointers 5 • A Pointer is a variable which holds the address of another variable of same data type. • Pointers provide the following benefits –  Facilitates function call by reference.  Enable a function to return more than one value.  Allocate memory dynamically (at run time).  Improves program execution speed.  Enables to access a variable that is defined outside the function. • Pointer declaration syntax – DataType *PointerVariableName; • Pointer initialization syntax – PointerVariableNam = &NormalVariableName; • Example – int *p, a = 10; p = &a; www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Concepts of Pointers 6 •The & is called the reference operator. The use of reference operator is called referencing and it provides the “address of” a variable. • The * is called the dereference operator. The use of dereference operator is called dereferencing and it provides the “value pointed by” a pointer. •The content of pointer and normal variables is shown below: www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Concepts of Pointers 7 #include<stdio.h> Output – void main () Value of x= 5 { Value of x= 5 int x, *p; Address of x = 2211 p = &x; Address of x = 2211 *p = 5; Address of p = 4321 printf(\"\\n Value of x= %d\", x); printf(\"\\n Value of x = %d\", *p); printf(\"\\n Address of x = %u\", &x); printf(\"\\n Address of x = %u\", p); printf(\"\\n Address of p = %u, &p); } Unit- 8(BCA112) All right are reserved with CU-IDOL www.cuidol.in

NULL Pointer 8 • A Null Pointer is a pointer that does not point to any #include <stdio.h> memory location. It has value NULL. void main() { • It is used to initialize o pointer variable when the pointer does not point to a valid memory address. int *ptr=NULL; if(ptr != NULL) • It perform error handling in pointer related code e.g. { dereference pointer variable only if it’s not NULL. printf(\"value of ptr is : %d\",*ptr); • Example- int *q = NULL; } else www.cuidol.in Unit- 8(BCA112) { printf(\"Invalid pointer\"); } } All right are reserved with CU-IDOL

Pointer Arithmetic 9 • A pointer holds an address, that is numeric in nature. • You can perform arithmetic operations on a pointer similar as you do with numeric data. • The arithmetic operations can be performed on pointer is ++ (increment)  - - (decrement) + (addition) and - (subtraction) • Comparison of two pointers are allowed. www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Pointer Arithmetic 10 #include<stdio.h> void main() { int c[4]={11,34,23,55},*p1 = &c[1], *p2 = &c[3], *p3= &c[0]; // c[0] stored at location 2020, and int with 2 bytes size. printf(\"Value of p3 = %u\\n\", p3); //2020 printf(\"Value of p3 = %u\\n\", ++p3); //2022 printf(\"Value of p3 = %u\\n\", --p3); //2020 printf(\"Value of p3+2 = %u\\n\", p3+2); //2024 printf(\"Value of p3-1 = %u\\n\", p3-1); //2022 printf(\"Value of p2-p1 = %u\\n\", p2-p1); //2, Returns number of elements from one to the other. printf(\"Value of *p2-*p1 = %u\\n\", *p2 - *p1); // 21 printf(\"Value of *p2+*p1 = %u\\n\", *p2 + *p1); // 89 printf(\"Value of *p2 * *p1 = %u\\n\", *p2 * *p1); // 1870 } www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Pointer Arithmetic 11 • Comparison of two pointers are allowed. www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Pointers and Arrays 12 • Arrays and pointers are closely related in C Example – programming void main() { • An array name is really a pointer to the first int x[5] ={51,42,83,14,65}, i, *p ; element in the array. p = &x[0]; // p = x; • Declare an array x[ 5 ] and a pointer xPtr for(i=0;i<5;i++, p++) xPtr = x; // xPtr = &x[ 0 ]; printf(“\\n x[i] = %d and *p =%d”, x[i], *p)); } • Element x[ 3 ] Can be accessed by *( xPtr + 3 ) or *( x + 3 ) www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Array of Pointers 13 • Arrays can contain pointers • For example: an array of strings char *suit[ 4 ] = { \"Hearts\", \"Diamonds\", \"Clubs\", \"Spades\" }; Strings are pointers to the first character char * – each element of suit is a pointer to a char The strings are not actually stored in the array suit, only pointers to the strings are stored suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\\0’ suit[1] ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\\0’ suit[2] ’C’ ’l’ ’u’ ’b’ ’s’ ’\\0’ suit[3] ’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’\\0’ suit array has a fixed size, but strings can be of any size www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Array of Pointers 14 www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Array of Pointers 15 Multidimentional Arrays- #include<stdio.h> void main() { Int i; char *arr[4] = {“C”,”C++”,”java”,”VBA”}; char *(*ptr)[4]=&arr; for(i=0;i<4;i++) printf(“Address of String %d : %u\\n”,i+1,(*ptr)[i]); } OUTPUT Address Of String 1 = 278 Address Of String 2 = 280 Address Of String 3 = 284 Address Of String 4 = 289 www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Pointers and Function 16 • Functions can take pointer as parameters. #include <stdio.h> void swap( int *a, int *b ) •Such use of pointer is referred to as passing { int temp; reference (address/location). temp = *a; •.Call by reference - Changes made to the *a = *b; formal argument will be reflected to actual *b = temp; arguments. printf(\"\\n In swap after swapping: a= %d, b= %d\", *a,*b); Output – } Before swapping: a= 10, b= 20 In swap after swapping: a= 20, b= 10 void main( ) In main after swapping: a= 20, b= 10 { int a = 10, b = 20 ; www.cuidol.in Unit- 8(BCA112) printf(\"Before swapping: a= %d, b= %d\", a, b); swap(&a, &b); printf(\"\\n In main after swapping: a= %d, b= %d\", a, b); } All right are reserved with CU-IDOL

Basics of Dynamic Memory 17 Allocation • Allocating memory at run time is known as dynamic memory allocation. • Memory is allocated during the execution of the program as per user requirements. • Dynamic memory is managed and served using pointers that point to the newly allocated space. • There are many advantages of dynamic memory allocation –  We can prevent wastage of memory.  We can allocate additional storage whenever we need it.  We can de-allocate dynamic space whenever we are done with it. • Disadvantage of DMA is that memory needs to be freed by the user when done. www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Basics of Dynamic 18 Memory Allocation Static Memory Allocation vs. Dynamic Memory Allocation www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Dynamic Memory Allocation 19 Functions The main four functions used for performing DMA are - • malloc() : Allocates requested size of bytes and returns a pointer to the first byte of the allocated space. • calloc() : Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. • free() : Frees previously allocated space. • realloc(): Modifies the size of previously allocated space. www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Dynamic Memory Allocation 20 Functions malloc() •. The name malloc stands for “memory allocation”. • malloc() function is used to allocate space in memory during the execution of the program. • malloc() does not initialize the memory allocated during execution. It carries garbage value. • malloc() function returns null pointer if it couldn’t able to allocate requested amount of memory. • The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form. www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Dynamic Memory Allocation Functions 21 • Syntax of malloc() ptr = (cast-type*) Example - malloc(byte-size) • Example – ptr = (int*) malloc(100 * sizeof(int)); #include <stdio.h> Output: #include <string.h> Dynamically allocated memory content: Welcome #include <stdlib.h> int main() { char *mem_allocation; mem_allocation = malloc( 8 * sizeof(char) ); if( mem_allocation== NULL ) { printf(“Couldn’t able to allocate requested memory\\n”); } else { strcpy( mem_allocation, “Welcome”); } printf(“Dynamically allocated memory content : “%s\\n”, mem_allocation ); free(mem_allocation); } www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Dynamic Memory Allocation 22 Functions calloc() •By using calloc() we can create the memory dynamically at initial stage. •calloc() required 2 arguments of type count, size-type. •calloc() will creates the memory in blocks format. •Initial value of the memory is zero •The difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero. www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Dynamic Memory Allocation 23 Functions • Syntax of calloc() Example - ptr = (cast-type*)calloc(n, element-size); #include <stdio.h> • Example – ptr = (float*) calloc(25, sizeof(float)); #include <string.h> Output: #include <stdlib.h> Dynamically allocated memory content: Welcome int main() { char *mem_allocation; mem_allocation = calloc(20, sizeof(char)); if( mem_allocation== NULL ) { printf(“Couldn’t able to allocate requested memory\\n”); } else { strcpy( mem_allocation, “Welcome”); } printf(“Dynamically allocated memory content : “%s\\n”, mem_allocation ); free(mem_allocation); } www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Dynamic Memory Allocation 24 Functions Difference between malloc() and calloc() Functions www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Dynamic Memory Allocation 25 Functions realloc() •realloc() function modifies the allocated memory size by malloc() and calloc() functions to new size. •If enough space doesn’t exist in memory of current block to extend, new block is allocated for the full size of reallocation, then copies the existing data to new block and then frees the old block. •By using realloc() we can create the memory dynamically at middle stage. •realloc() will creates the memory in bytes format and initial value is garbage. www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Dynamic Memory Allocation 26 Functions • Syntax of realloc() Example - ptr = realloc(ptr, newsize); #include <stdio.h> Here, ptr is reallocated with size of newsize #include <stdlib.h> www.cuidol.in void main() { int *ptr, i , n1, n2; printf(“Enter size of array: “); scanf(“%d”, &n1); ptr = (int*) malloc(n1 * sizeof(int)); printf(“Address of previously allocated memory: “); for(i = 0; i < n1; ++i) printf(“%u\\t”,ptr + i); printf(“\\nEnter new size of array: “); scanf(“%d”, &n2); ptr = realloc(ptr, n2); for(i = 0; i < n2; ++i) printf(“%u\\t”, ptr + i); } Unit- 8(BCA112) All right are reserved with CU-IDOL

Dynamic Memory Allocation 27 Functions free() •free() function frees the allocated memory by malloc(), calloc(), realloc() functions and returns the memory to the system. •Dynamically allocated memory created with either calloc() or malloc() doesn’t get freed on its own. You must explicitly use free() to release the space. www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Dynamic Memory Allocation 28 Functions • Syntax of free() - free(ptr); printf(“Dynamically allocated memory content : %s\\n”, This statement frees the space allocated in mem_allocation ); the memory pointed by ptr. mem_allocation=realloc(mem_allocation,100*sizeof(char) ); Example - if( mem_allocation == NULL ) #include <stdio.h> {printf(“Couldn’t able to allocate requested memory\\n”);} #include <stdlib.h> else void main() {strcpy( mem_allocation,\"space is extended up to 100 { characters”);} char *mem_allocation; printf(“Resized memory : %s\\n”, mem_allocation ); mem_allocation = malloc( 20 * sizeof(char) ); free(mem_allocation); if( mem_allocation == NULL ) getch( ); { printf(“Couldn’t able to allocate requested } memory\\n”); } Output: else Dynamically allocated memory content : God is great {strcpy( mem_allocation,” God is great “); } Resized memory : space is extended up to 100 characters www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Multiple Choice Questions 29 1. A pointer is a) A variable that stores address of an instruction b) A variable that stores address of other variable c) A keyword used to create variables d) None of these 2. What do the following declaration signify? char *arr[10]; a) arr is a array of 10 character pointers b) arr is a array of function pointer c) arr is a array of characters d) Arr is a pointer to array of characters Answers: 1.b) 2.a) www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Multiple Choice Questions 30 3. What is the output of this C code? int x = 0; void main() { int *ptr = &x; printf(\"%u\\n\", ptr); x++; printf(\"%u\\n \", ptr); } a) Same address b) Different address c) Compilation error d) Depends on machine Answers: 3. a) www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

Multiple Choice Questions 31 4. Which of the following is NOT correct? a) calloc() allocates the memory and also initializes the allocates memory to zero, while memory allocated using malloc() has random data. b) malloc() and memset() can be used to get the same effect as calloc(). c) calloc() takes two arguments, but malloc takes only 1 argument. d) None of the above 5. What is the return type of malloc() or calloc() a) void * * b) Pointer of allocated memory type c) void * d) int * Answers: 4. d 5.c www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

SUMMARY 32 Let us recapitulate the important concepts discussed in this session: • A Pointer is a variable which holds the address of another variable of same data type. •Pointers provide the following benefits – o Facilitates function call by reference. o Enable a function to return more than one value. o Allocate memory dynamically (at run time). o Improves program execution speed. o Enables to access a variable that is defined outside the function. •The & is called the reference operator. The use of reference operator is called referencing and it provides the “address of” a variable. •The * is called the dereference operator. The use of dereference operator is called dereferencing and it provides the “value pointed by” a pointer. •A Null Pointer is a pointer that does not point to any memory location. It has value NULL. •It is used to initialize o pointer variable when the pointer does not point to a valid memory address. •A pointer holds an address, that is numeric in nature. www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

SUMMARY 33 •You can perform arithmetic operations on a pointer similar as you do with numeric data. •Arrays and pointers are closely related in C programming. An array name is really a pointer to the first element in the array. •Arrays can contain pointers. •Functions can take pointer as parameters. Such use of pointer is referred to as passing reference (address/location). •Allocating memory at run time is known as dynamic memory allocation. •Advantage of DMA is that we can prevent wastage of memory. •Disadvantage of DMA is that memory needs to be freed by the user when done. •The main four functions used for performing DMA are - malloc() : Allocates requested size of bytes and returns a pointer to the first byte of the allocated space. calloc() : Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. free() : Frees previously allocated space. realloc(): Modifies the size of previously allocated space. www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

FREQUENTLY ASKED QUESTIONS 34 Q1. Define pointer. List out its benefits. Ans. A Pointer is a variable which holds the address of another variable of same data type. For further details please refer to the subject SLM unit 8. Q2. Differentiate between reference and dereference operators. Ans: The & is called the reference operator. The * is called the dereference operator. For further details please refer to the subject SLM unit 8. Q3. Describe pointer arithmetic. Ans: A pointer holds an address, that is numeric in nature. You can perform arithmetic operations on a pointer similar as you do with numeric data. For further details please refer to the subject SLM unit 8. Q4: What is meant by null pointer. Mention its use. Ans: A Null Pointer is a pointer that does not point to any memory location. It has value NULL. For further details please refer to the subject SLM unit 8. www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

FREQUENTLY ASKED QUESTIONS 35 Q5. What is meant by dynamic memory allocation? Mention its advantages. Ans. Allocating memory at run time is known as dynamic memory allocation. For further details please refer to the subject SLM unit 8. Q6. Compare static and dynamic memory allocation. Ans. In static memory allocation, memory is allocated while writing the C program. Actually, user requested memory will be allocated at compile time. While in dynamic memory allocation, memory is allocated while executing the program. For further details please refer to the subject SLM unit 8. Q7. Differentiate between malloc() and calloc() functions. Ans. The difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero. For further details please refer to the subject SLM unit 8. Q8: Why we use free() and realloc() functions in DMA? Ans. Dynamically allocated memory created with either calloc() or malloc() doesn’t get freed on its own. You must explicitly use free() to release the space. For further details please refer to the subject SLM unit 8. www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

REFERENCES 36 • CU-IDOL’s “Computer Programming” SLM • Balaguruswamy (2017).Programming in ANSI C. New Delhi: McGraw-Hill. • Kanetkar, Y. (2014), Programming in C ANSI standard.New Delhi: BPB Publications. • Gottfried (2005).Programming with C. New York: Tata McGraw Hill. • Harrow K., Jones J. (1996).Problem Solving with C. London: Pearson Education. • Jeri R., Hanly,KoffmanE.P. (2000).Problem Solving and Program Design in C. 3rd Ed. Boston: Addison Wesley. www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL

37 THANK YOU www.cuidol.in Unit- 8(BCA112) All right are reserved with CU-IDOL


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook