#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Function to allocate memory and initialize the string
char* allocateString(size_t size, const char *initialValue) {
char *str = malloc(size * sizeof(char));
if (str == NULL) {
perror("Failed to allocate memory");
return NULL;
}
strcpy(str, initialValue);
return str;
}
// Function to resize and append content to a string
char* resizeAndAppend(char *str, const char *append) {
size_t newSize = strlen(str) + strlen(append) + 1;
char *temp = realloc(str, newSize * sizeof(char));
if (temp == NULL) {
perror("Failed to reallocate memory");
free(str); // Clean up original memory
return NULL;
}
str = temp;
strcat(str, append);
return str;
}
int main() {
// Use the function to allocate and initialize
char *str = allocateString(6, "Hello");
if (str == NULL) return 1;
// Resize and append more text
str = resizeAndAppend(str, " C Programming");
if (str == NULL) return 1;
printf("Resized string: %s\n", str);
// Free memory
free(str);
return 0;
}
/*
run:
Resized string: Hello C Programming
*/