Pointer
82 / 100

Unit-2 Pointers- C Programming | BCA 2nd Sem

Unit-2 Pointers- C Programming | BCA 2nd Sem- Hello everyone welcome to the pencilchampions.com website. This website provide Unit-2 Pointers- C Programming | BCA 2nd Sem  CCS University Notes. Thankyou for visiting.

Pointer

Unit-2

Pointers

Meaning of Pointer

  • A pointer is a concept in programming that allows us to store and manipulate memory addresses. It’s like having a signpost that points to a specific location in the computer’s memory.
  • In simpler terms, think of memory as a big warehouse with different storage locations. Each location has a unique address. A pointer is like a note that tells us the address of a specific location in the warehouse.
  • Pointers are commonly used in programming languages like C and C++. They are powerful tools that enable us to work with memory directly and efficiently. Here’s an example to help illustrate the concept:
  • Let’s say we have a variable called “num” that stores the value 10. The variable “num” is stored in a specific memory location. We can use a pointer to store the address of that memory location.

int num = 10;

int *ptr = #

  • In this example, we declared a pointer variable called “ptr” and assigned it the address of the variable “num” using the “&” operator. Now, the pointer “ptr” points to the memory location of “num”.
  • Pointers allow us to perform operations like accessing and modifying the value at the memory location they point to. For example, we can use the pointer to change the value of “num” directly:

*ptr = 20;

  • In this case, we used the “*” operator to access the value stored at the memory location pointed to by “ptr” and changed it to 20. Now, if we print the value of “num”, it will be 20.
  • Pointers are especially useful when working with large data structures like arrays or when dynamically allocating memory. They allow us to efficiently manipulate and pass around memory addresses instead of copying large amounts of data.

Readmore- https://pencilchampions.com/unit-1-array-c-programming-bca-2nd-sem/


How to Use Pointers

  • To use pointers, you first need to declare a pointer variable. In languages like C and C++, you can declare a pointer by using the asterisk (*) symbol. For example:

int *ptr;

  • This declares a pointer variable called “ptr” that can store the memory address of an integer variable.
  • Next, you can assign a memory address to the pointer variable. This can be done by using the address-of operator (&) followed by the variable you want to get the address of. For example:

int num = 10;

ptr = #

  • In this example, we assign the address of the variable “num” to the pointer “ptr”. Now, “ptr” points to the memory location where “num” is stored.
  • Once you have a pointer that points to a memory location, you can use it to access or modify the value at that location. To access the value, you use the dereference operator (*) in front of the pointer variable. For example:

int value = *ptr;

  • In this case, the dereference operator (*) retrieves the value stored at the memory location pointed to by “ptr” and assigns it to the variable “value”.
  • You can also modify the value at the memory location using the dereference operator. For example:

*ptr = 20;

  • This changes the value at the memory location pointed to by “ptr” to 20.
  • Pointers are particularly useful when working with arrays. When you declare an array, its name is actually a pointer to the first element of the array. You can use pointer arithmetic to access other elements of the array. For example:

int arr[3] = {10, 20, 30};

int *ptr = arr;  // pointer to the first element of the array

  • int secondElement = *(ptr + 1); // accessing the second element using pointer arithmetic
  • In this example, we use pointer arithmetic to access the second element of the array by adding 1 to the pointer “ptr” and then dereferencing it.

Wikipedia- https://en.wikipedia.org/wiki/C_(programming_language)


NULL Pointers

  • A null pointer is a special value that a pointer variable can hold when it doesn’t point to any valid memory location. It’s like a placeholder that indicates the absence of a valid address.
  • In many programming languages, including C and C++, a null pointer is represented by the value “NULL” or “0”. When a pointer is assigned the value NULL, it means that it doesn’t currently point to anything meaningful.
  • Null pointers are commonly used in error handling, dynamic memory allocation, and as a sentinel value to indicate the end of a data structure. For example, when you allocate memory dynamically using functions like malloc(), calloc(), or new, if the allocation fails, the function returns a null pointer to indicate that no memory could be allocated.
  • To check if a pointer is null, you can simply compare it to the null value. For example:

int *ptr = NULL;

if (ptr == NULL) {

    // Pointer is null, handle the error or absence of valid memory location

}

  • In this example, we assign the value NULL to the pointer variable “ptr” and then check if it is equal to NULL. If it is, we can handle the error or absence of a valid memory location in some way.
  • It’s important to note that dereferencing a null pointer, that is, trying to access the value it points to, can lead to undefined behavior and crashes in your program. So, always make sure to check if a pointer is null before using it to avoid such issues.
  • To assign a null value to a pointer, you can use the literal “NULL” or “0”, or you can use the preprocessor macro “nullptr” in C++.
  • Null pointers are a helpful concept in programming, as they allow you to handle cases where a pointer doesn’t have a valid memory address. Just remember to handle null pointers appropriately to avoid any unexpected behavior in your code.

Indirection Operator

  • The indirection operator, also known as the dereference operator, is represented by the asterisk symbol (*) in many programming languages, including C and C++.
  • The indirection operator is used to access the value stored at the memory location pointed to by a pointer variable. It allows you to retrieve the value that the pointer is pointing to, rather than just the memory address itself.
  • To understand how the indirection operator works, let’s consider an example:

int num = 42;

int *ptr = #

// Using the indirection operator to access the value

int value = *ptr;

  • In this example, we have an integer variable num with a value of 42. We also have a pointer variable ptr, which is assigned the memory address of num using the address-of operator (&). The ptr variable now points to num.
  • Now, using the indirection operator (*), we can retrieve the value stored at the memory location pointed to by ptr. In this case, *ptr would give us the value of num, which is 42. We then assign this value to the variable value.
  • The indirection operator is particularly useful when working with dynamically allocated memory. For example, when you allocate memory for an array or a structure using functions like malloc(), calloc(), or new, you can use the indirection operator to access and manipulate the values stored in that memory.
  • It’s important to note that the indirection operator should only be used with valid pointers. Dereferencing a null pointer or a pointer that doesn’t point to a valid memory location can lead to undefined behavior and crashes in your program.
  • So, the indirection operator allows you to access the value stored at the memory location pointed to by a pointer variable. It’s a powerful tool in programming that enables you to work with the actual data rather than just the memory addresses. Just remember to use it with caution and ensure that your pointers are valid before dereferencing them.

Address Operators

  • The address operators are used to obtain the memory address of a variable in a programming language. They allow you to access and manipulate the memory location where a variable is stored.
  • In many programming languages, such as C and C++, there are two main address operators: the ampersand (&) and the arrow operator (->).
  • The ampersand operator (&) is used to get the address of a variable. It allows you to retrieve the memory location where a variable is stored. For example:

int num = 42;

int *ptr = #

  • In this example, the variable num is assigned the value 42. The ampersand operator (&) is then used to get the address of num, which is stored in the pointer variable ptr. Now, ptr points to the memory location where num is stored.
  • The arrow operator (->) is used to access members of a structure or a class through a pointer. It combines the dereference operator (*) and the dot operator (.) into a single operator. For example:

struct Person {

    char name[20];

    int age;

};

struct Person *personPtr;

personPtr = malloc(sizeof(struct Person));

strcpy(personPtr->name, “John”);

personPtr->age = 25;

  • In this example, we have a structure called Person with members name and age. We allocate memory for a Person structure using malloc(), and the address of the allocated memory is stored in the personPtr pointer.
  • To access the members of the Person structure through the pointer, we use the arrow operator (->). We can assign values to the name and age members using the arrow operator.
  • It’s important to note that the address operators should be used with caution. Dereferencing a null pointer or accessing an invalid memory location can lead to undefined behavior and crashes in your program.
  • Address operators are particularly useful when working with pointers, dynamic memory allocation, and passing variables by reference. They allow you to manipulate memory directly and efficiently.
  • So, the address operators, such as the ampersand (&) and the arrow operator (->), are used to obtain the memory address of a variable and access members of a structure or class through a pointer. They are powerful tools in programming that enable you to work with memory locations and manipulate data efficiently.

Pointer Arithmetic in C

  • Pointer arithmetic allows you to perform arithmetic operations on pointers in C programming language. It’s a powerful feature that enables you to navigate through memory and access elements in arrays or structures.
  • In C, when you perform arithmetic operations on a pointer, it is automatically scaled based on the size of the data type it points to. For example, if you have a pointer to an integer (int *ptr), incrementing the pointer by 1 will make it point to the next integer in memory, not just the next byte.
  • Here are some common pointer arithmetic operations:
  1. Incrementing a pointer:

   int arr[5] = {1, 2, 3, 4, 5};

   int *ptr = arr;  // Pointer to the first element of the array

   ptr++;  // Moves the pointer to the next element in the array

  1. Decrementing a pointer:

   int *ptr = &arr[4];  // Pointer to the last element of the array

   ptr–;  // Moves the pointer to the previous element in the array

  1. Adding an offset to a pointer:

   int *ptr = arr;  // Pointer to the first element of the array

   ptr += 2;  // Moves the pointer two elements ahead in the array

  1. Subtracting an offset from a pointer:

   int *ptr = &arr[3];  // Pointer to the fourth element of the array

   ptr -= 2;  // Moves the pointer two elements back in the array

  1. Accessing elements using pointer arithmetic:

   int *ptr = arr;  // Pointer to the first element of the array

   int thirdElement = *(ptr + 2);  // Accesses the third element of the array

  • It’s important to note that pointer arithmetic should be used with caution to avoid accessing memory outside the allocated range. Also, pointer arithmetic is only valid within the same array or memory block.
  • Pointer arithmetic is particularly useful when working with arrays, iterating through data structures, or implementing algorithms that require efficient memory traversal.

Incrementing Pointer in C

  • When you increment a pointer in C, you’re essentially moving it to the next memory location based on the size of the data type it points to.

Here’s how you can increment a pointer in C:

  1. Incrementing by 1:

   int arr[5] = {1, 2, 3, 4, 5};

   int *ptr = arr;  // Pointer to the first element of the array

   ptr++;  // Moves the pointer to the next memory location

  • In this example, we have an array of integers called arr. We initialize a pointer ptr to point to the first element of the array. By using the ++ operator, we increment the pointer, which makes it point to the next memory location, which is the second element in this case.
  1. Incrementing by multiple elements:

   int *ptr = arr;  // Pointer to the first element of the array

   ptr += 2;  // Moves the pointer two elements ahead in the array

  • In this case, we increment the pointer by 2, which moves it two elements ahead in the array. This is useful when you want to skip over certain elements or access specific elements in the array.
  • It’s important to note that when incrementing a pointer, you should ensure that you stay within the bounds of the allocated memory. Incrementing beyond the allocated memory can lead to unexpected behavior or accessing invalid memory locations.
  • Pointer incrementation is commonly used in scenarios where you need to iterate through an array or traverse a data structure. By incrementing the pointer, you can easily access the next element or move to the desired location in memory.
  • Remember, pointer arithmetic should be used responsibly and with caution to avoid any memory-related issues. It’s always a good practice to double-check your code and ensure that you’re incrementing the pointer correctly.

Decrementing Pointer in C

  • When you decrement a pointer in C, you’re essentially moving it to the previous memory location based on the size of the data type it points to.

Here’s how you can decrement a pointer in C:

  1. Decrementing by 1:

   int arr[5] = {1, 2, 3, 4, 5};

   int *ptr = &arr[4];  // Pointer to the last element of the array

 ptr–;  // Moves the pointer to the previous memory location

  • In this example, we have an array of integers called arr. We initialize a pointer ptr to point to the last element of the array using the & operator. By using the — operator, we decrement the pointer, which makes it point to the previous memory location, which is the fourth element in this case.
  1. Decrementing by multiple elements:

   int *ptr = &arr[4];  // Pointer to the last element of the array

   ptr -= 2;  // Moves the pointer two elements back in the array

  • In this case, we decrement the pointer by 2, which moves it two elements back in the array. This is useful when you want to skip over certain elements or access specific elements in reverse order.
  • Just like with incrementing pointers, it’s important to ensure that you stay within the bounds of the allocated memory when decrementing pointers. Decrementing beyond the allocated memory can lead to unexpected behavior or accessing invalid memory locations.
  • Decrementing pointers can be useful in scenarios where you need to iterate through an array or traverse a data structure in reverse order. By decrementing the pointer, you can easily access the previous element or move to the desired location in memory.
  • Remember to use pointer arithmetic responsibly and with caution to avoid any memory-related issues. Double-check your code and make sure you’re decrementing the pointer correctly.

C Pointer Addition

  • When you add an integer value to a pointer in C, you’re essentially moving the pointer forward in memory by a certain number of elements based on the size of the data type it points to.

Here’s how you can perform pointer addition in C:

  1. Adding an integer value to a pointer:

   int arr[5] = {1, 2, 3, 4, 5};

   int *ptr = &arr[0];  // Pointer to the first element of the array

   ptr += 2;  // Moves the pointer two elements forward in the array

  • In this example, we have an array of integers called arr. We initialize a pointer ptr to point to the first element of the array using the & operator. By using the += operator, we add 2 to the pointer, which moves it two elements forward in the array.
  1. Adding a multiple of the data type size:

   int *ptr = &arr[0];  // Pointer to the first element of the array

   ptr += 3 * sizeof(int);  // Moves the pointer three elements forward in the array

  • In this case, we add 3 * sizeof(int) to the pointer. The sizeof(int) gives us the size of the integer data type in bytes. By multiplying it with the number of elements we want to move forward, we can accurately increment the pointer by the desired number of elements.
  • Pointer addition can be useful when you want to access specific elements in an array or traverse a data structure. By adding an integer value to the pointer, you can easily move to the desired location in memory.
  • Just like with pointer decrementing, it’s important to ensure that you stay within the bounds of the allocated memory when performing pointer addition. Adding beyond the allocated memory can lead to unexpected behavior or accessing invalid memory locations.
  • Remember to use pointer arithmetic responsibly and with caution to avoid any memory-related issues. Double-check your code and make sure you’re adding the correct value to the pointer.

C Pointer Subtraction

  • When you subtract an integer value from a pointer in C, you’re essentially moving the pointer backward in memory by a certain number of elements based on the size of the data type it points to.

Here’s how you can perform pointer subtraction in C:

  1. Subtracting an integer value from a pointer:

   int arr[5] = {1, 2, 3, 4, 5};

   int *ptr = &arr[4];  // Pointer to the last element of the array

   ptr -= 2;  // Moves the pointer two elements backward in the array

  • In this example, we have an array of integers called arr. We initialize a pointer ptr to point to the last element of the array using the & operator. By using the -= operator, we subtract 2 from the pointer, which moves it two elements backward in the array.
  1. Subtracting a multiple of the data type size:

   int *ptr = &arr[4];  // Pointer to the last element of the array

   ptr -= 3 * sizeof(int);  // Moves the pointer three elements backward in the array

  • In this case, we subtract 3 * sizeof(int) from the pointer. The sizeof(int) gives us the size of the integer data type in bytes. By multiplying it with the number of elements we want to move backward, we can accurately decrement the pointer by the desired number of elements.
  • Pointer subtraction can be useful when you want to access specific elements in an array or traverse a data structure in reverse order. By subtracting an integer value from the pointer, you can easily move to the desired location in memory.
  • Just like with pointer addition, it’s important to ensure that you stay within the bounds of the allocated memory when performing pointer subtraction. Subtracting beyond the allocated memory can lead to unexpected behavior or accessing invalid memory locations.

Illegal arithmetic with Pointers

  • In C, there are certain arithmetic operations that are not allowed with pointers, such as multiplication, division, and bitwise operations. These operations are only valid for integers, not pointers.
  • For example, you cannot multiply or divide a pointer by an integer value. This is because the result would not make sense in terms of memory addresses.

Here’s an example of illegal arithmetic with pointers:

int *ptr = some_address;

ptr = ptr * 2;  // Illegal: Multiplying a pointer by an integer

  • In this example, we’re trying to multiply the pointer ptr by 2, which is not allowed. The result would be an invalid memory address and could lead to unexpected behavior.
  • It’s important to stick to legal operations when working with pointers in C. This means using pointer arithmetic for addition and subtraction with integer values, as we discussed earlier. Any other arithmetic operations should be performed on the values that the pointers point to, not the pointers themselves.
  • If you ever come across a situation where you need to perform complex arithmetic operations involving pointers, it’s best to rethink your approach and find an alternative solution. Keeping your code clean and avoiding illegal operations will help ensure the stability and correctness of your program.

Pointer to function in C

  • In C, you can create a pointer that points to a function. This allows you to treat functions as variables and pass them around as arguments or store them in data structures. It’s a powerful feature that enables you to implement things like function callbacks and function pointers.

Here’s an example of how you can declare and use a pointer to a function in C:

C

#include <stdio.h>

// Function declaration

void greet() {

    printf(“Hello, friend!\n”);

}

// Function that takes a function pointer as an argument

void callGreeting(void (*func)()) {

    func();  // Calling the function through the function pointer

}

int main() {

    // Declaring a function pointer variable

    void (*ptr)() = greet;

    // Calling the function through the function pointer

    ptr();

    // Passing the function pointer as an argument

    callGreeting(ptr);

    return 0;

}

  • In this example, we have a function called greet() that simply prints a greeting message. We declare a function pointer variable called ptr that points to the greet() function. We can then call the function through the function pointer by using the () operator.
  • We also have another function called callGreeting() that takes a function pointer as an argument. Inside this function, we call the function through the function pointer by using the () operator again.
  • Function pointers can be really useful when you want to implement dynamic behavior in your code or when you need to pass functions as arguments to other functions. They provide flexibility and allow you to create more modular and reusable code.

Pointer to Array of functions in C

  • In C, you can create a pointer that points to an array of functions. This allows you to treat the array of functions as a single entity and access individual functions through the pointer. It can be useful in scenarios where you want to dynamically select and call different functions from an array.

Here’s an example of how you can declare and use a pointer to an array of functions in C:

C

#include <stdio.h>

// Function declarations

void add(int a, int b) {

    printf(“Sum: %d\n”, a + b);

}

void subtract(int a, int b) {

    printf(“Difference: %d\n”, a – b);

}

void multiply(int a, int b) {

    printf(“Product: %d\n”, a * b);

}

int main() {

    // Declaring an array of function pointers

    void (*funcArr[3])(int, int) = {add, subtract, multiply};

    // Declaring a pointer to the array of function pointers

    void (**ptr)(int, int) = funcArr;

    // Calling functions through the pointer to the array of function pointers

    ptr[0](4, 2);  // Calls the add function

    ptr[1](4, 2);  // Calls the subtract function

    ptr[2](4, 2);  // Calls the multiply function

    return 0;

}

  • In this example, we have three functions (add(), subtract(), and multiply()) that perform different mathematical operations. We declare an array of function pointers called funcArr that holds the addresses of these functions. Then, we declare a pointer to the array of function pointers called ptr and initialize it to point to funcArr.
  • We can access individual functions in the array through the pointer by using the index operator []. For example, ptr[0] points to the add() function, ptr[1] points to the subtract() function, and so on. We can then call these functions through the pointer.
  • Using a pointer to an array of functions allows you to have a more flexible and dynamic way of working with multiple functions. You can easily add or remove functions from the array and access them through the pointer.

Dynamic memory allocation in C

  • In C, dynamic memory allocation allows you to allocate and deallocate memory at runtime, rather than at compile time. This can be useful when you need to allocate memory for data structures whose size is not known beforehand or when you want to allocate memory as needed during program execution.
  • To allocate dynamic memory in C, you can use the malloc() function. It stands for “memory allocation” and is defined in the stdlib.h header file. Here’s an example:

C

#include <stdio.h>

#include <stdlib.h>

int main() {

    int size;

    int *dynamicArray;

    printf(“Enter the size of the array: “);

    scanf(“%d”, &size);

    // Allocate memory dynamically

    dynamicArray = (int *)malloc(size * sizeof(int));

    if (dynamicArray == NULL) {

        printf(“Memory allocation failed. Exiting…\n”);

        return 1;

    }

    printf(“Memory allocation successful!\n”);

    // Use the dynamically allocated memory as needed

    // Deallocate the memory when done

    free(dynamicArray);

    return 0;

}

  • In this example, we first prompt the user to enter the size of the array they want to allocate dynamically. We store the size in the variable size. Then, we use the malloc() function to allocate memory for an array of integers. The expression size * size of(int) calculates the total number of bytes needed for the array based on the size.
  • After allocating the memory, we check if the allocation was successful by comparing the pointer dynamic Array to NULL. If it’s NULL, it means the allocation failed, and we handle the error accordingly.
  • If the allocation is successful, we can use the dynamically allocated memory as needed. Once we are done using it, it’s important to deallocate the memory using the free() function. This frees up the memory and makes it available for other parts of the program to use.
  • Dynamic memory allocation in C gives you more flexibility in managing memory during program execution. Just remember to deallocate the memory when you’re done with it to avoid memory leaks.

Malloc() function in C

  • The malloc() function in C is used for dynamic memory allocation. It stands for “memory allocation” and is defined in the stdlib.h header file.
  • With malloc(), you can allocate memory at runtime based on the size you specify. It returns a pointer to the allocated memory block, or NULL if the allocation fails.

Here’s an example of how to use malloc():

C

#include <stdio.h>

#include <stdlib.h>

int main() {

    int *ptr;

    int numElements;

    printf(“Enter the number of elements: “);

    scanf(“%d”, &numElements);

    // Allocate memory dynamically

    ptr = (int *)malloc(numElements * sizeof(int));

    if (ptr == NULL) {

        printf(“Memory allocation failed. Exiting…\n”);

        return 1;

    }

    printf(“Memory allocation successful!\n”);

    // Use the dynamically allocated memory as needed

    // Deallocate the memory when done

    free(ptr);

    return 0;

}

  • In this example, we prompt the user to enter the number of elements they want to allocate dynamically. We store the value in the variable numElements. Then, we use malloc() to allocate memory for an array of integers. The expression numElements * sizeof(int) calculates the total number of bytes needed for the array based on the number of elements.
  • After allocating the memory, we check if the allocation was successful by comparing the pointer ptr to NULL. If it’s NULL, it means the allocation failed, and we handle the error accordingly.
  • If the allocation is successful, we can use the dynamically allocated memory as needed. Once we are done using it, it’s important to deallocate the memory using the free() function. This frees up the memory and makes it available for other parts of the program to use.

Calloc() function in C

The calloc() function in C is used for dynamic memory allocation, just like the malloc() function. The main difference is that calloc() also initializes the allocated memory to zero.

Here’s an example of how to use calloc():

c

#include <stdio.h>

#include <stdlib.h>

int main() {

    int *ptr;

    int numElements;

    printf(“Enter the number of elements: “);

    scanf(“%d”, &numElements);

    // Allocate memory dynamically and initialize to zero

    ptr = (int *)calloc(numElements, sizeof(int));

    if (ptr == NULL) {

        printf(“Memory allocation failed. Exiting…\n”);

        return 1;

    }

    printf(“Memory allocation successful!\n”);

    // Use the dynamically allocated memory as needed

    // Deallocate the memory when done

    free(ptr);

    return 0;

}

  • In this example, we prompt the user to enter the number of elements they want to allocate dynamically. We store the value in the variable numElements. Then, we use calloc() to allocate memory for an array of integers. The first argument to calloc() is the number of elements, and the second argument is the size of each element in bytes.
  • After allocating the memory, we check if the allocation was successful by comparing the pointer ptr to NULL. If it’s NULL, it means the allocation failed, and we handle the error accordingly.
  • If the allocation is successful, we can use the dynamically allocated memory as needed. Since calloc() initializes the memory to zero, we don’t need to explicitly set the values.
  • Once we are done using the memory, it’s important to deallocate it using the free() function, just like with malloc()

Realloc() function in C

  • The realloc() function in C is used for dynamically resizing previously allocated memory. It allows you to change the size of a previously allocated block of memory.

Here’s an example of how to use realloc():

C

#include <stdio.h>

#include <stdlib.h>

int main() {

    int *ptr;

    int numElements;

    printf(“Enter the initial number of elements: “);

    scanf(“%d”, &numElements);

    // Allocate memory dynamically

    ptr = (int *)malloc(numElements * sizeof(int));

    if (ptr == NULL) {

        printf(“Memory allocation failed. Exiting…\n”);

        return 1;

    }

    printf(“Memory allocation successful!\n”);

    // Use the dynamically allocated memory as needed

    int newNumElements;

    printf(“Enter the new number of elements: “);

    scanf(“%d”, &newNumElements);

    // Reallocate memory to resize the block

    ptr = (int *)realloc(ptr, newNumElements * sizeof(int));

    if (ptr == NULL) {

        printf(“Memory reallocation failed. Exiting…\n”);

        return 1;

    }

    printf(“Memory reallocation successful!\n”);

    // Use the resized memory as needed

    // Deallocate the memory when done

    free(ptr);

    return 0;

}

  • In this example, we first prompt the user to enter the initial number of elements they want to allocate dynamically. We store the value in the variable numElements. Then, we use malloc() to allocate memory for an array of integers.
  • After allocating the memory, we check if the allocation was successful by comparing the pointer ptr to NULL. If it’s NULL, it means the allocation failed, and we handle the error accordingly.
  • If the allocation is successful, we can use the dynamically allocated memory as needed.
  • Next, we prompt the user to enter the new number of elements they want after resizing. We store the value in the variable new Num Elements. Then, we use realloc() to resize the previously allocated block of memory. The first argument to realloc() is the pointer to the previously allocated memory, and the second argument is the new size of the block in bytes.
  • Again, we check if the reallocation was successful by comparing the pointer ptr to NULL. If it’s NULL, it means the reallocation failed, and we handle the error accordingly.

Free() function in C

  • The free() function in C is used to deallocate memory that was previously allocated dynamically using functions like malloc(), calloc(), or realloc(). It helps in releasing the memory back to the operating system so that it can be reused.

Here’s an example of how to use free():

C

#include <stdio.h>

#include <stdlib.h>

int main() {

    int *ptr;

    int numElements;

    printf(“Enter the number of elements: “);

    scanf(“%d”, &numElements);

    // Allocate memory dynamically

    ptr = (int *)malloc(numElements * sizeof(int));

    if (ptr == NULL) {

        printf(“Memory allocation failed. Exiting…\n”);

        return 1;

    }

    printf(“Memory allocation successful!\n”);

    // Use the dynamically allocated memory as needed

    // Deallocate the memory when done

    free(ptr);

    printf(“Memory deallocation successful!\n”);

    return 0;

}

  • In this example, we first prompt the user to enter the number of elements they want to allocate dynamically. We store the value in the variable numElements. Then, we use malloc() to allocate memory for an array of integers.
  • After allocating the memory, we check if the allocation was successful by comparing the pointer ptr to NULL. If it’s NULL, it means the allocation failed, and we handle the error accordingly.
  • If the allocation is successful, we can use the dynamically allocated memory as needed.
  • Finally, when we are done using the dynamically allocated memory, we use the free() function to deallocate the memory. We pass the pointer to the memory block that we want to deallocate as the argument to free(). This releases the memory back to the operating system.

Discover more from Pencil Champions

Subscribe to get the latest posts sent to your email.

Leave a Reply

Discover more from Pencil Champions

Subscribe now to keep reading and get access to the full archive.

Continue reading