BM Balmiki Mandal 09 Sep 2023 15 views 0 comments C Programming

Managing Memory: Freeing Allocated Memory for Pointer Arrays

Freeing Allocated Memory for an Array of Pointers

To free the memory allocated for an array of pointers, you need to iterate through each element of the array and free the memory allocated for each individual pointer. After that, you can free the memory allocated for the array itself.

Here's an example code snippet in C:

C-programming
#include <stdio.h>
#include <stdlib.h>

int main() {
    int i;
    int n = 5; // Assuming you have an array of 5 pointers

    // Allocate memory for an array of pointers
    char* array_of_pointers[n];

    for (i = 0; i < n; i++) {
        // Allocate memory for each individual pointer
        array_of_pointers[i] = (char*)malloc(20 * sizeof(char)); // Assuming each string has a maximum length of 19 characters
    }

    // ... Do operations with the array of pointers ...

    // Free the memory for each individual pointer
    for (i = 0; i < n; i++) {
        free(array_of_pointers[i]);
    }

    // Free the memory for the array of pointers
    return 0;
}

In this example, we first allocate memory for an array of pointers array_of_pointers. Then, we loop through each element and allocate memory for individual strings using malloc.

After performing operations with the strings, we free the memory for each individual string using free(array_of_pointers[i]). Finally, we free the memory for the array of pointers using return 0;.

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Bit wise operators Assignment

Bitwise Operators practical assignment: Take runtime input, bit-level manipulation, and different data units r...

AG Anvesh G 27 Sep 2026
Understanding Float and Double Binary Representation in C

Understanding Float and Double Binary Representation in CIntroduction:When we store decimal numbers such as 10...

AG Anvesh G 31 May 2026
Topic-wise C Programming Interview Questions

C Programming Interview Questions – Topic Wise1. IntroductionC programming is one of the most important langu...

AG Anvesh G 30 May 2026