Unit 7 Pointer And Dynamic Memory Allocation PDF
Document Details
Uploaded by ChasteLouisville
Marwadi University
Tags
Summary
These lecture notes covers computer programming, explaining pointers in C, and dynamic memory allocation. It includes examples and explains various concepts related to pointers in C.
Full Transcript
Department of CE 01CE0101 - Computer Unit - 7 Pointers and Programming Dynamic Memory Allocation The pointer is a variable which stores the address of another variable. This variable can be of type...
Department of CE 01CE0101 - Computer Unit - 7 Pointers and Programming Dynamic Memory Allocation The pointer is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer. Example: to define a pointer which stores the address of an integer. Pointer int n = 10; Int*p = &n; // Variable p of type pointe r is pointing to the address of the variable n of type integer. The pointer in c language can be declared using * (asterisk symbol). Declaring It is also known as indirection pointer a pointer used to dereference a pointer. int *a; //pointer to int char *c; //pointer to char Pointer Here pointer variable stores the address Example of number variable, i.e., fff4. The value of number variable is 50. But the address of pointer variable p is aaa3. By the help of * (indirection operator), we can print the value of pointer variable p. #include int main() { int number=50; int *p; Example p=&number; printf("Address of p variable is %x \n",p); printf("Value of p variable is %d \n",*p); return 0; } Pointer to an array is also known as array pointer. We are using the pointer to access the components of the array. Pointer to Example: array int arr; int *p=&arr; // Variable p of type pointer is pointing to the address of an integer array arr. A pointer to a function points to the address of the executable code of the function. You can use pointers to call functions and to pass functions as Pointer to arguments to other functions. a function You cannot perform pointer arithmetic on pointers to functions. Example void show (int); void(*p)(int) = &display; // Pointer p is pointing to the address of a function The type of a pointer to a function is based on both the return type and parameter types of the function. A declaration of a pointer to a function must have the pointer name in parentheses. Function parameters have Pointer to precedence over pointers in a function declarations, so parentheses are required to alter the precedence and declare a pointer to a function. Without them, the compiler interprets the declaration as a function that returns a pointer to a specified return type 1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc. and used with arrays, Advantage structures, and functions. of pointer 2) We can return multiple values from a function using the pointer. 3) It makes you able to access any memory location in the computer's memory. There are many applications of pointers in c language. 1) Dynamic memory allocation In c language, we can dynamically allocate Usage of memory using malloc() and calloc() pointer functions where the pointer is used. 2) Arrays, Functions, and Structures Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and improves the performance. The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable. Example Address Of #include (&) int main() Operator { int number=50; printf("value of number is %d, address of number is %u",number,&number); return 0; } We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we know that pointer contains the address, the result of an arithmetic operation performed on the pointer will also be a pointer if the other operand is of type Pointer integer. Arithmetic In pointer-from-pointer subtraction, the result will be an integer value. Following arithmetic operations are possible on the pointer Increment Decrement Addition Subtraction Comparison If we increment a pointer by 1, the pointer will start pointing to the immediate next location. It different from the general arithmetic since the value of the pointer will get increased by the size of the data type to which the pointer is pointing. We can traverse an array by using the Incrementi increment operation on a pointer which will keep pointing to every element of the array, ng Pointer perform some operation on that, and update itself in a loop. Syntax: new_address= current_address + i * size_of(data type) Where i is the number by which the pointer get increased. #include int main() { int number=50; int *p;//pointer to int p=&number;//stores the address of number Example variable printf("Address of p variable is %u \n",p); p=p+1; printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incremented by 4 bytes. return 0; } Like increment, we can decrement a pointer variable. If we decrement a pointer, it will Decrement start pointing to the previous location. ing Syntax: Pointer new_address= current_address - i * size_of(dat a type) #include void main() { int number=50; int *p;//pointer to int p=&number;//stores the address of number variable Example printf("Address of p variable is %u \n",p); p=p-1; printf("After decrement: Address of p variable is %u \ n",p); // P will now point to the immidiate previous location. } We can add a value to the pointer variable Pointer Syntax: Addition new_address= current_address + (number * size_of(data type)) #include int main() { int number=50; int *p;//pointer to int Pointer p=&number;// stores the address of number variable Addition printf("Address of p variable is %u \n",p); p=p+3; //adding 3 to pointer variable printf("After adding 3: Address of p variable is %u \ n",p); return 0; } Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number from a Pointer pointer will give an address. The Subtractio formula of subtracting value from the n pointer variable is given below: Syntax: new_address= current_address - (number * size_of(data type)) #include int main(){ int number=50; int *p;//pointer to int Pointer p=&number;//stores the address of number variable Subtractio printf("Address of p variable is %u \n",p); n p=p-3; //subtracting 3 from pointer variable printf("After subtracting 3: Address of p variable is %u \n",p); return 0; } Pointer Program to swap two numbers without using the 3rd variable. #include int main() { Swapping int a=10,b=20,*p1=&a,*p2=&b; using printf("Before swap: *p1=%d *p2=%d",*p1,*p2); pointer *p1=*p1+*p2; *p2=*p1-*p2; *p1=*p1-*p2; printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2); return 0; } Dynamic Memory Allocation A pointer that is not assigned any value but NULL is known as the NULL pointer. If you don't have any address to be specified in the pointer at the time of NULL declaration, you can assign NULL value. Pointer It will provide a better approach. Example int *p=NULL; In the most libraries, the value of the pointer is 0 (zero). #include int main() { NULL // Null Pointer Pointer int *ptr = NULL; printf("The value of ptr is %p", ptr); return 0; } Void pointer is a specific pointer type – void * – a pointer that points to some data location in storage, which doesn’t have any specific type. Void Void refers to the type. Pointer void pointers cannot be dereferenced. It can however be done using typecasting the void pointer Pointer arithmetic is not possible on pointers of void due to lack of concrete value and thus size. #include int main() { int x = 4; o/p: Integer variable is = 4 float y = 5.5; Float variable is = 5.50000 Void // A void pointer Pointer void* ptr; ptr = &x; // void pointer variable. printf("Integer variable is = %d", *((int*)ptr)); // void pointer is now float ptr = &y; printf("\nFloat variable is = %f", *((float*)ptr)); return 0; } The Dynamic memory allocation enables the C programmers to allocate memory at runtime. DMA can be defined as a procedure in which the size of a data structure is changed during the runtime. Dynamic There are 4 library functions provided by C Memory defined under header file to facilitate Allocatio dynamic memory allocation in C programming. They are: n malloc() calloc() free() realloc() “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. malloc() It returns a pointer of type void which can be cast into a pointer of method any form. It initializes each block with default garbage value. Syntax: ptr = (cast-type*) malloc(byte- size) For Example: ptr = (int*) malloc(100 * sizeof(int)); Example Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory. “calloc” or “contiguous allocation” method in C 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’. calloc() Syntax: method ptr = (cast-type*)calloc(n, element-size); For Example: ptr = (float*) calloc(25, sizeof(float)); This statement allocates contiguous space in memory for 25 elements each with the size of the float. calloc() method “free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions free() malloc() and calloc() is not de- method allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it. Syntax: free(ptr); free() method “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is realloc() insufficient, realloc can be used to dynamically re-allocate memory. method re-allocation of memory maintains the already present value and new blocks will be initialized with default garbage value. Syntax: ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'. realloc() method Dangling A pointer pointing to a memory location that has been Pointer deleted (or freed) is called dangling pointer.