How to increase the size of dynamic string in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h> 

int main(void)
{
    char *s, *tmp;
    int len = 15;

    s = malloc(len * sizeof(char));
    strcpy(s, "c programming");
    puts(s);

    tmp = realloc(s, (len * 2) * sizeof(char)); 
    if (tmp != NULL)
    {
        strcat(s, " is fun");
        len *= 2;;
    }
    else
    {
        free(tmp);
        printf("Error allocating memory!\n");
        return 1;
    }      
    
    puts(s);

    free(s);

    return 0;
}
/*
run:
c programming
c programming is fun
*/



answered Sep 13, 2014 by avibootz
edited Sep 13, 2014 by avibootz
...