Certainly! Below is a simple C code example that demonstrates how to create an array and then resize it to fit one more element, using the malloc and realloc functions from the C Standard Library:
#include <stdio.h>
#include <stdlib.h> // Required for malloc, realloc, and free
int main() {
int initial_size = 5;
int new_size = initial_size + 1; // Increase the size by 1
int *array;
// Allocate memory for the initial array
array = (int *)malloc(initial_size * sizeof(int));
if (array == NULL) {
fprintf(stderr, "Memory allocation failed!\n");
return 1;
}
// Initialize the array with some values
for (int i = 0; i < initial_size; ++i) {
array[i] = i; // Assign value i to the ith element
}
// Resize the array to fit one more element
int *new_array = (int *)realloc(array, new_size * sizeof(int));
if (new_array == NULL) {
fprintf(stderr, "Memory reallocation failed!\n");
free(array); // Free the original array if realloc fails
return 1;
}
array = new_array; // Update the pointer in case realloc moved the block
// Initialize the new element
array[initial_size] = initial_size; // Assign value to the new element
// Print the resized array contents
printf("Resized array elements:\n");
for (int i = 0; i < new_size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
// Free the allocated memory
free(array);
return 0;
}
This program starts by allocating memory for an array of five integers. It then initializes these integers with the values 0 through 4. After that, the program uses realloc to resize the array so that it can hold one additional integer, and it initializes this new element with its corresponding value. Finally, the program prints out the elements of the resized array and frees the allocated memory before exiting.
Please note that memory allocation can fail if the system is out of memory, so it's a good practice to always check the return value of malloc and realloc. Also, if realloc fails, it returns NULL and the original block of memory remains valid