Complementary task for topic: 7

M Nemeth · 2023-08-29 15:21:04.623218'

DStrings: An example

DStrings: An example

In C, dynamic strings are usually implemented using pointers and dynamic memory allocation. Unlike fixed-size character arrays, dynamic strings can resize themselves at runtime to accommodate the data being stored. This flexibility allows dynamic strings to handle strings of varying lengths without wasting memory.
To create dynamic strings, you typically use the following steps:
> Declare a pointer to a character (char*) to hold the dynamic string.
> Allocate memory for the dynamic string using functions like malloc() or calloc().
> Use the dynamic string to store data, manipulate it as needed, and update its size when necessary.
> Deallocate the memory used by the dynamic string when it is no longer needed using free().

Hint: Now, just follow the solution

Solution
#include 
#include 
#include 

int main() {
    char* dynamicString = NULL; //Declaration, NULL is not mandatory, but it helps when we do not know if the DString contains anything

    // Allocate memory for the dynamic string
    dynamicString = (char*)malloc(10 * sizeof(char));

    if (dynamicString == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    // Initialize the dynamic string
    strcpy(dynamicString, "Hello");//It will fit we have 9 character space in the string 

    // Append more characters to the dynamic string
    dynamicString = (char*)realloc(dynamicString, 20 * sizeof(char));

    if (dynamicString == NULL) {//Maybe it wont work, better to use malloc and strcpy
        printf("Memory reallocation failed.\n");
        free(dynamicString); // Free allocated memory before returning
        return 1;
    }

    strcat(dynamicString, ", World!");

    // Print and use the dynamic string
    printf("%s\n", dynamicString);

    // Deallocate the memory used by the dynamic string
    free(dynamicString);

    return 0;
}



Explanation
In this example, we use malloc() to allocate memory for the dynamic string and initialize it with "Hello". Then, we use realloc() to resize the dynamic string and append ", World!" to it. Finally, we print the dynamic string and free the memory used by the dynamic string with free().

Remember that when using dynamic memory allocation, it's essential to deallocate the memory with free() to avoid memory leaks. Additionally, you should always check if the memory allocation and reallocation are successful by verifying if the returned pointer is not NULL.

Dynamic strings are useful when the size of the string is unknown at compile time or when dealing with large strings that may consume a significant amount of memory. However, managing dynamic memory comes with additional responsibilities, such as proper allocation, resizing, and deallocation, which need to be handled carefully to avoid memory-related bugs.
< < previous    next > >