#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
*/