Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,943 questions

51,883 answers

573 users

How to resize a string with realloc() in C

1 Answer

0 votes
#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

*/

 



answered Jul 19, 2025 by avibootz

Related questions

2 answers 157 views
1 answer 188 views
188 views asked May 19, 2025 by avibootz
2 answers 177 views
1 answer 64 views
2 answers 322 views
...