How to initialize and use a static pointer to allocate and initialize memory only one time in C

2 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>

void allocateMemoryOneTime() {
    static int* ptr = NULL; // Declare a static pointer and initialize it to NULL
    int total = 5;

    if (ptr == NULL) {
        ptr = (int*)malloc(total * sizeof(int));
        if (ptr == NULL) {
            printf("Memory allocation failed\n");
            exit(1);
        }

        // Initialize the allocated memory
        for (int i = 0; i < total; i++) {
            ptr[i] = i + 1;
        }

        printf("Memory allocated and initialized.\n");
    }
    else {
        printf("Memory already allocated.\n");
    }

    for (int i = 0; i < total; i++) {
        printf("%d ", ptr[i]);
    }
    printf("\n");
}

int main() {
    allocateMemoryOneTime(); // First call, memory will be allocated
    allocateMemoryOneTime(); // Second call, memory will not be allocated again
    allocateMemoryOneTime(); // Third call, memory will not be allocated again

    return 0;
}



/*
run:

Memory allocated and initialized.
1 2 3 4 5
Memory already allocated.
1 2 3 4 5
Memory already allocated.
1 2 3 4 5

*/

 



answered Aug 17, 2024 by avibootz
edited Aug 17, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>

#define TOTAL 7

void allocateMemoryOneTime() {
    static int* ptr = NULL; // Declare a static pointer and initialize it to NULL

    if (ptr == NULL) {
        ptr = (int*)malloc(TOTAL * sizeof(int));
        if (ptr == NULL) {
            printf("Memory allocation failed\n");
            exit(1);
        }

        // Initialize the allocated memory
        for (int i = 0; i < TOTAL; i++) {
            ptr[i] = i + 1;
        }

        printf("Memory allocated and initialized.\n");
    }
    else {
        printf("Memory already allocated.\n");
    }

    for (int i = 0; i < TOTAL; i++) {
        printf("%d ", ptr[i]);
    }
    printf("\n");
}

int main() {
    allocateMemoryOneTime(); // First call, memory will be allocated
    allocateMemoryOneTime(); // Second call, memory will not be allocated again
    allocateMemoryOneTime(); // Third call, memory will not be allocated again

    return 0;
}



/*
run:

Memory allocated and initialized.
1 2 3 4 5 6 7
Memory already allocated.
1 2 3 4 5 6 7
Memory already allocated.
1 2 3 4 5 6 7

*/


 



answered Aug 17, 2024 by avibootz

Related questions

1 answer 159 views
2 answers 273 views
1 answer 217 views
2 answers 160 views
1 answer 119 views
119 views asked Nov 30, 2023 by avibootz
1 answer 99 views
99 views asked Jan 31, 2023 by avibootz
...