C - Write program to allocate memory for string and do the character copy

Requirements

Create two char buffers by using a pointer and malloc().

After text is read by the fgets() function, copy that text from the first buffer into the second buffer.

Copy all the text except for the newline character, \n, at the end of input.

Demo

#include <stdio.h>
#include <stdlib.h>

int main()//from   w  w w .  j ava  2 s  .c  o m
{
    char *input1,*input2;
    char *i1,*i2;

    input1 = (char *)malloc(sizeof(char)*1024);
    input2 = (char *)malloc(sizeof(char)*1024);
    if(input1==NULL || input2==NULL)
    {
        puts("Unable to allocate buffer!");
        exit(1);
    }

    puts("Type something long:");
    fgets(input1,1023,stdin);

    puts("Copying buffer...");
    i1=input1; 
    i2=input2;
    
    while(*i1 != '\n'){
       *i2++=*i1++;
    }
    *i2 = '\0';

    printf("Original text:\n\"%s\"\n",input1);
    printf("Duplicate text:\n\"%s\"\n",input2);

    return(0);
}

Result

Related Exercise