Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Similar documents
Computer Programming Unit 3

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

Procedural programming with C

Tutorial 10 Pointers in C. Shuyue Hu

Chapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

Programming. Pointers, Multi-dimensional Arrays and Memory Management

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Pointers, Arrays, and Strings. CS449 Spring 2016

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

First of all, it is a variable, just like other variables you studied

Programming in C - Part 2

High Performance Programming Programming in C part 1

Kurt Schmidt. October 30, 2018

Variation of Pointers

[0569] p 0318 garbage

int marks[10]; // fixed size and fixed address No change in Memory address.

Fundamental of Programming (C)

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

CS 11 C track: lecture 5

Dynamic Data Structures. CSCI 112: Programming in C

Homework #3 CS2255 Fall 2012

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Unit IV & V Previous Papers 1 mark Answers

Content. In this chapter, you will learn:

Memory Allocation. General Questions

Intermediate Programming, Spring 2017*

POINTER & REFERENCE VARIABLES

MODULE V: POINTERS & PREPROCESSORS

Lab 3. Pointers Programming Lab (Using C) XU Silei

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

POINTER AND ARRAY SUNU WIBIRAMA

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Dynamic memory allocation (malloc)

Arrays, Pointers and Memory Management

The C Programming Language Part 4. (with material from Dr. Bin Ren, William & Mary Computer Science, and

Introduction to Scientific Computing and Problem Solving

Memory Management. CSC215 Lecture

Dynamic Allocation in C

Pointers and File Handling

Memory, Arrays & Pointers

C Structures & Dynamic Memory Management

Q. 1 What will be the output of the following program? Justify your answer. [4] #include <stdio.h> main(){ int i=4, a[5]={1,2,3,4,5};

Arrays and Pointers (part 1)

CS 61c: Great Ideas in Computer Architecture

Dynamic Memory Allocation

Pointers. 10/5/07 Pointers 1

PROGRAMMAZIONE I A.A. 2017/2018

2/28/2018. Overview. The C Programming Language Part 4. Pointers. Pointers. Pointers. Pointers

Fundamentals of Programming Session 20

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

Dynamic memory allocation

CS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

Dynamic Allocation in C

ESC101N: Fundamentals of Computing End-sem st semester

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

Memory Allocation in C

Arrays and Pointers (part 1)

Lecture 8 Dynamic Memory Allocation

In Java we have the keyword null, which is the value of an uninitialized reference type

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Pointers. Introduction

Pointer in C SHARDA UNIVERSITY. Presented By: Pushpendra K. Rajput Assistant Professor

Exam 3 Chapters 7 & 9

today cs3157-fall2002-sklar-lect05 1

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Pointers. September 13, 2017 Hassan Khosravi / Geoffrey Tien 1

Topics so far. Review. scanf/fscanf. How data is read 1/20/2011. All code handin sare at /afs/andrew/course/15/123/handin

MODULE 5: Pointers, Preprocessor Directives and Data Structures

CS201- Introduction to Programming Current Quizzes

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Arrays and Pointers in C. Alan L. Cox

C Pointers. Indirection Indirection = referencing a value through a pointer. Creating Pointers. Pointer Declarations. Pointer Declarations

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Subject: Fundamental of Computer Programming 2068

Lecture 04 Introduction to pointers

C for Java Programmers 1. Last Week. Overview of the differences between C and Java. The C language (keywords, types, functies, etc.

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

C-Refresher: Session 06 Pointers and Arrays

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

Pointers, Dynamic Data, and Reference Types

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Quick review pointer basics (KR ch )

A Fast Review of C Essentials Part I

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

Pointers and Arrays. Introduction To Pointers. Using The "Address Of" The Operator & Operator. Using The Dereference. The Operator * Operator

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

CSCI 171 Chapter Outlines

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

POINTERS. Content. Pointers. Benefits of Pointers. In this chapter, you will learn:

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

Transcription:

Jagannath Institute of Management Sciences Lajpat Nagar BCA II Sem C Programming

UNIT I Pointers: Introduction to Pointers, Pointer Notation,Decalaration and Initialization, Accessing variable through pointer, Pointer Expression, Pointer and One Dimensional Arrays, Malloc, Calloc Library, Pointer to pointer. A pointer is a constant or variable that contains an address that can be used to access data. Pointers are built on the basic concept of pointer constants C programming tasks can be performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect C programmer. Every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Character Constants and Variables Pointer Constant:

Pointer constants, drawn from the set of addresses for a computer, exist by themselves. We cannot change them; we can only use them. An address expression, one of the expression types in the unary expression category, consists of an ampersand (&) and a variable name. Print Character Addresses Consider the following example, which will print the address of the variables defined: #include <stdio.h> int main () int var1; char var2[10]; printf("address of var1 variable: %x\n", &var1 );

printf("address of var2 variable: %x\n", &var2 ); return 0; When the above code is compiled and executed, it produces result something as follows: Address of var1 variable Address of var2 variable : bff5a400 : bff5a3f6 Integer Constants and Variables What Are Pointers? A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is: type *var-name; Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration: Pointer Variable Declaration

int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character */ The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to. More Example:

How to use Pointers? There are few important operations, which we will do with the help of pointers very frequently. (a) We define a pointer variable (b) Assign the address of a variable to a pointer and (c) Finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations: #include <stdio.h> int main () int var = 20; /* actual variable declaration */ int *ip; /* pointer variable declaration */ ip = &var; /* store address of var in pointer variable*/ printf("address of var variable: %x\n", &var ); /* address stored in pointer variable */ printf("address stored in ip variable: %x\n", ip ); /* access the value using the pointer */ printf("value of *ip variable: %d\n", *ip ); return 0; When the above code is compiled and executed, it produces result something as follows: Address of var variable : bffd8b3c

Address stored in ip variable : bffd8b3c Value of *ip variable : 20 Demonstrate Use of Pointers Multiple Pointers to a Variable

NULL Pointers in C It is always a good practice to assig n a NULL value to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer. The NULL pointer is a constant with a value of zero defined in several standard libraries. A pointer that points to no variable contains the special null-pointer constant, NULL. Consider the following program: #include <stdio.h> int main () int *ptr = NULL; printf("the value of ptr is : %x\n", ptr ); return 0; When the above code is compiled and executed, it produces the following result: The value of ptr is 0 On most of the operating systems, prog rams are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to nothing. To check for a null pointer you can use an if statement as follows: if(ptr) /* succeeds if p is not null */ if(!ptr) /* succeeds if p is null */

An indirect expression, one of the expression types in the unary expression category, is coded with an asterisk (*) and an identifier. Accessing Variables through Pointers Address and Indirection Operators Uninitialized Pointers

Initializing Pointer Variables Fun with Pointers

Demonstrate Pointer Flexibility Using One Pointer for Many Variables

C - POINTER ARITHMETIC C pointer is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can a numeric value. There are four arithmetic operators that can be used on pointers: 1) ++ 2) -- 3) + 4) - To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer:

ptr++ Now, after the above operation, the ptr will point to the location 1004 because each time ptr is incremented, it will point to the next integer location which is 4 bytes next to the current location. This operation will move the pointer to next memory location without impacting actual value at the memory location. If ptr points to a character whose address is 1000, then above operation will point to the location 1001 because next character will be available at 1001. Incrementing a Pointer We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. The following program increments the variable pointer to access each succeeding element of the array: #include <stdio.h> const int MAX = 3; int main () int var[] = 10, 100, 200; int i, *ptr; /* let us have array address in pointer */ ptr = var; for ( i = 0; i < MAX; i++) printf("address of var[%d] = %x\n", i, ptr ); printf("value of var[%d] = %d\n", i, *ptr ); /* move to the next location */ ptr++; return 0;

When the above code is compiled and executed, it produces result something as follows: Address of var[0] = bf882b30 Value of var[0] = 10 Address of var[1] = bf882b34 Value of var[1] = 100 Address of var[2] = bf882b38 Value of var[2] = 200 Decrementing a Pointer The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of its data type as shown below: #include <stdio.h> const int MAX = 3; int main () int var[] = 10, 100, 200; int i, *ptr; /* let us have array address in pointer */ ptr = &var[max-1]; for ( i = MAX; i > 0; i--) printf("address of var[%d] = %x\n", i, ptr ); printf("value of var[%d] = %d\n", i, *ptr ); /* move to the previous location */ ptr--;

return 0; When the above code is compiled and executed, it produces result something as follows: Address of var[3] = bfedbcd8 Value of var[3] = 200 Address of var[2] = bfedbcd4 Value of var[2] = 100 Address of var[1] = bfedbcd0 Value of var[1] = 10 Pointer Comparisons Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to variables that are related to each other, such as elements of the same array, then p1 and p2 can be meaning fully compared. The following program modifies the previous example one by incrementing the variable pointer so long as the address to which it points is either less than or equal to the address of the last element of the array, which is &var[max - 1]: #include <stdio.h> const int MAX = 3; int main () int var[] = 10, 100, 200; int i, *ptr;

/* let us have address of the first element in pointer */ ptr = var; i = 0; while ( ptr <= &var[max - 1] ) printf("address of var[%d] = %x\n", i, ptr ); printf("value of var[%d] = %d\n", i, *ptr ); /* point to the previous location */ ptr++; i++; return 0; When the above code is compiled and executed, it produces result something as follows: Address of var[0] = bfdbcb20 Value of var[0] = 10 Address of var[1] = bfdbcb24 Value of var[1] = 100 Address of var[2] = bfdbcb28 Value of var[2] = 200 POINTER TO AN ARRAY IN C

An array name is a constant pointer to the first element of the array. Therefore, in the declaration: double balance[50]; balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assig ns p the address of the first element of balance: double *p; double balance[10]; p = balance; It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4]. Once you store the address of first element in p, you can access array elements using *p, *(p+1), *(p+2) and so on. Below is the example to show all the concepts discussed above: #include <stdio.h> int main () /* an array with 5 elements */ double balance[5] = 1000.0, 2.0, 3.4, 17.0, 50.0; double *p; int i; p = balance; /* output each array element's value */ printf( "Array values using pointer\n"); for ( i = 0; i < 5; i++ ) printf("*(p + %d) : %f\n", i, *(p + i) );

printf( "Array values using balance as address\n"); for ( i = 0; i < 5; i++ ) printf("*(balance + %d) : %f\n", i, *(balance + i) ); return 0; When the above code is compiled and executed, it produces the following result: Array values using pointer *(p + 0) : 1000.000000 *(p + 1) : 2.000000 *(p + 2) : 3.400000 *(p + 3) : 17.000000 *(p + 4) : 50.000000 Array values using balance as address *(balance + 0) : 1000.000000 *(balance + 1) : 2.000000 *(balance + 2) : 3.400000 *(balance + 3) : 17.000000 *(balance + 4) : 50.000000 In the above example, p is a pointer to double, which means it can store address of a variable of double type. Once we have address in p, then *p will give us value available at the address stored in p, as we have shown in the above example. C - POINTER TO POINTER

A pointer to a pointer is a form of multiple indirections, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below. A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, following is the declaration to declare a pointer to a pointer of type int: int **var; When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown below in the example: #include <stdio.h> int main () int var; int *ptr; int **pptr; var = 3000; /* take the address of var */ ptr = &var; /* take the address of ptr using address of operator & */ pptr = &ptr; /* take the value using pptr */ printf("value of var = %d\n", var ); printf("value available at *ptr = %d\n", *ptr ); printf("value available at **pptr = %d\n", **pptr); return 0; When the above code is compiled and executed, it produces the following result: Value of var = 3000

Value available at *ptr = 3000 Value available at **pptr = 3000 PASSING POINTERS TO FUNCTIONS IN C C programming language allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type. Following a simple example where we pass an unsigned long pointer to a function and change the value inside the function which reflects back in the calling function: #include <stdio.h> #include <time.h> void getseconds(unsigned long *par); int main () unsigned long sec; getseconds( &sec ); /* print the actual value */ printf("number of seconds: %ld\n", sec ); return 0; void getseconds(unsigned long *par) /* get the current number of seconds */ *par = time( NULL ); return; When the above code is compiled and executed, it produces the following result: Number of seconds: 1294450468 The function, which can accept a pointer, can also accept an array as shown in the following example: #include <stdio.h> /* function declaration */

double getaverage(int *arr, int size); int main () /* an int array with 5 elements */ int balance[5] = 1000, 2, 3, 17, 50; double avg; /* pass pointer to the array as an argument */ avg = getaverage( balance, 5 ) ; /* output the returned value */ printf("average value is: %f\n", avg ); return 0; double getaverage(int *arr, int size) int i, sum = 0; double avg; for (i = 0; i < size; ++i) sum += arr[i]; avg = (double)sum / size; return avg; When the above code is compiled together and executed, it produces the following result: Average value is: 214.40000 PASSING ARRAYS AS FUNCTION ARGUMENTS IN C If you want to pass a sing le-dimension array as an argument in a function, you would have to declare function formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received. Similar way you can pass multidimensional array as formal parameters.

Way-1 Formal parameters as a pointer as follows. You will study what is pointer in next chapter. void myfunction(int *param)... Way-2 Formal parameters as a sized array as follows: void myfunction(int param[10])... Way-3 Formal parameters as an unsized array as follows: void myfunction(int param[])... Example Now, consider the following function, which will take an array as an argument along with another argument and based on the passed arguments, it will return average of the numbers passed through the array as follows: double getaverage(int arr[], int size)

int i; double avg; double sum; for (i = 0; i < size; ++i) sum += arr[i]; avg = sum / size; return avg; Now, let us call the above function as follows: #include <stdio.h> /* function declaration */ double getaverage(int arr[], int size); int main () /* an int array with 5 elements */ int balance[5] = 1000, 2, 3, 17, 50; double avg; /* pass pointer to the array as an argument */ avg = getaverage( balance, 5 ) ; /* output the returned value */ printf( "Average value is: %f ", avg ); return 0;

When the above code is compiled together and executed, it produces the following result: Average value is: 214.400000 As you can see, the length of the array doesn't matter as far as the function is concerned because C performs no bounds checking for the formal parameters. Pointers for Inter-function Communication: Passing Addresses Functions Returning Pointers An Unworkable Exchange

Exchange Using Pointers Every time we want a called function to have access to a variable in the calling function, we pass the address of that variable to the called function and use the indirection operator to access it. Functions Returning Pointers

It is a serious error to return a pointer to a local variable. Pointers to Pointers So far, all our pointers have been pointing directly to data. It is possible and with advanced data structures often necessary to use pointers that point to other pointers. For example, we can have a pointer pointing to a pointer to an integer.

Using Pointers to Pointers

Compatibility It is important to recognize that pointers have a type associated with them. They are not just pointer types, but rather are pointers to a specific type, such as character. Each pointer therefore takes on the attributes of the type to which it refers in addition to its own attributes. Pointer Size Compatibility Dereference Type Compatibility Dereference Level Compatibility Demonstrate Size of Pointers

Dereference Type Compatibility A void pointer cannot be dereferenced. Dereference Level Compatibility

Lvalue and Rvalue In C, an expression is either an lvalue or an rvalue. As you know, every expression has a value. But the value in an expression (after evaluation) can be used in two different ways. Pointer Examples lvalue Expressions

The right operand of an assignment operator must be an rvalue expression. Operators That Require lvalue Expressions Invalid rvalue Expressions

Convert Seconds to Hours, Minutes, and Seconds

Create local variables when a value parameter will be changed within a function so that the original value will always be available for processing. When several values need to be sent back to the calling function, use address parameters for all of them. Do not return one value and use address Parameters for the others? A Common Program Design Using Pointers as Parameters

Dynamic Memory Allocation The process of allocating memory at runtime is known as dynamic memory allocation. 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. Function Description

malloc() allocates requested size of bytes and returns a void pointer pointing to the first byte of the allocated space calloc() allocates space for an array of elements, initialize them to zero and then return a void pointer to the memory free releases previously allocated memory realloc modify the size of previously allocated space Memory Allocation Process Global variables, static variables and program instructions get their memory in permanent storage area whereas local variables are stored in 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.

Allocating block of Memory malloc() function is used for allocating block of memory at runtime. This function reserves a block of memory of given size and returns a pointer of type void. This means that we can assign it to any type of pointer using typecasting. If it fails to locate enough space it returns a NULL pointer. Example using malloc() : int *x; x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable x free(x); //releases the memory allocated to variable x calloc() is another memory allocation function that is used for allocating memory at runtime. calloc function is normally used for allocating memory to derived data types such as arrays and structures. If it fails to locate enough space it returns a NULL pointer. Example using calloc() : struct employee char *name; int salary; ; typedef struct employee emp; emp *e1; e1 = (emp*)calloc(30,sizeof(emp)); realloc() changes memory size that is already allocated to a variable. Example using realloc() : int *x; x=(int*)malloc(50 * sizeof(int)); x=(int*)realloc(x,100); //allocated a new memory to variable x Diffrence between malloc() and calloc() calloc() malloc() calloc() initializes the allocated memory with 0 value. malloc() initializes the allocated memory with garbage values. Number of arguments is 2 Number of argument is 1

calloc() malloc() Syntax : (cast_type *)calloc(blocks, size_of_block); Syntax : (cast_type *)malloc(size_in_bytes); Description The C library function void *calloc(size_t nitems, size_t size) allocates the requested memory and returns a pointer to it. The difference in malloc and calloc is that malloc does not set the memory to zero where as calloc sets allocated memory to zero. Declaration Following is the declaration for calloc() function. void *calloc(size_t nitems, size_t size) Parameters nitems -- This is the number of elements to be allocated. size -- This is the size of elements. Return Value This function returns a pointer to the allocated memory, or NULL if the request fails. Example The following example shows the usage of calloc() function. #include <stdio.h> #include <stdlib.h> int main()

int i, n; int *a; printf("number of elements to be entered:"); scanf("%d",&n); a = (int*)calloc(n, sizeof(int)); printf("enter %d numbers:\n",n); for( i=0 ; i < n ; i++ ) scanf("%d",&a[i]); printf("the numbers entered are: "); for( i=0 ; i < n ; i++ ) printf("%d ",a[i]); free( a ); return(0); Let us compile and run the above program that will produce the following result: Number of elements to be entered:3 Enter 3 numbers: 22 55 14 The numbers entered are: 22 55 14 C Dynamic memory allocation DYNAMIC MEMORY ALLOCATION IN C: The process of allocating memory during program execution is called dynamic memory allocation.

DYNAMIC MEMORY ALLOCATION FUNCTIONS IN C: C language offers 4 dynamic memory allocation functions. They are, 1. malloc() 2. calloc() 3. realloc() 4. free() Function Syntax malloc () malloc (number *sizeof(int)); calloc () calloc (number, sizeof(int)); realloc () realloc (pointer_name, number * sizeof(int)); free () free (pointer_name); 1. MALLOC() FUNCTION IN C: 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. EXAMPLE PROGRAM FOR MALLOC() FUNCTION IN C: 1 2 3 #include <stdio.h> #include <string.h> #include <stdlib.h> 4 5 6 7 8 9 10 int main() char *mem_allocation; /* memory is allocated dynamically */ mem_allocation = malloc( 20 * sizeof(char) ); if( mem_allocation== NULL )

11 12 printf("couldn't able to allocate requested memory\n"); 13 14 15 16 17 18 19 20 else strcpy( mem_allocation,"fresh2refresh.com"); printf("dynamically allocated memory content : " \ "%s\n", mem_allocation ); free(mem_allocation); 21 OUTPUT: Dynamically allocated memory content : fresh2refresh.com 2. CALLOC() FUNCTION IN C: calloc () function is also like malloc () function. But calloc () initializes the allocated memory to zero. But, malloc() doesn t. EXAMPLE PROGRAM FOR CALLOC() FUNCTION IN C: 1 2 3 #include <stdio.h> #include <string.h> #include <stdlib.h> 4 5 6 7 8 int main() char *mem_allocation; /* memory is allocated dynamically */

9 10 11 12 13 14 15 16 17 18 19 20 mem_allocation = calloc( 20, sizeof(char) ); if( mem_allocation== NULL ) printf("couldn't able to allocate requested memory\n"); else strcpy( mem_allocation,"fresh2refresh.com"); printf("dynamically allocated memory content : " \ "%s\n", mem_allocation ); free(mem_allocation); 21 OUTPUT: Dynamically allocated memory content : fresh2refresh.com 3. REALLOC() FUNCTION IN C: 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. 4. FREE() FUNCTION IN C: free () function frees the allocated memory by malloc (), calloc (), realloc () functions and returns the memory to the system. EXAMPLE PROGRAM FOR REALLOC() AND FREE() FUNCTIONS IN C: 1 2 #include <stdio.h> #include <string.h> 3 #include <stdlib.h> 4

5 int main() 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 char *mem_allocation; /* memory is allocated dynamically */ mem_allocation = malloc( 20 * sizeof(char) ); if( mem_allocation == NULL ) printf("couldn't able to allocate requested memory\n"); else strcpy( mem_allocation,"fresh2refresh.com"); printf("dynamically allocated memory content : " \ "%s\n", mem_allocation ); mem_allocation=realloc(mem_allocation,100*sizeof(char)); if( mem_allocation == NULL ) printf("couldn't able to allocate requested memory\n"); else strcpy( mem_allocation,"space is extended upto " \ "100 characters"); printf("resized memory : %s\n", mem_allocation ); free(mem_allocation); 32 OUTPUT:

Dynamically allocated memory content : fresh2refresh.com Resized memory : space is extended upto 100 characters DIFFERENCE BETWEEN STATIC MEMORY ALLOCATION AND DYNAMIC MEMORY ALLOCATION IN C: Static memory allocation Dynamic memory allocation In static memory allocation, memory is allocated while writing the C program. Actually, user requested memory will be allocated at compile time. In dynamic memory allocation, memory is allocated while executing the program. That means at run time. Memory size can t be modified while execution. Example: array Memory size can be modified while execution. Example: Linked list DIFFERENCE BETWEEN MALLOC() AND CALLOC() FUNCTIONS IN C: 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 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) );