I want to save some characters from one string to another.

I tried going from character to character from one string and saving them to the other string.

#include <stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    char *sent, *rec;
    int i, a;
    sent = malloc(100);
    rec = malloc(100);
    gets(sent);
    a = strlen(sent);
    for (i = 0; i < 3; i++)
        *(rec + i) = *(sent + i);
    a = strlen(rec);
    rec = realloc(rec, 4);
    puts(rec);
}

If I input "Hello world" the expected output should be"Hel", but it is "Hel" and some random characters.And also I dont understand why is the lenght of rec equal to 14.

1 Answers

1
P__J__ On Best Solutions
memcpy(rec,sent,3)
rec[3] = 0;

or more general

memcpy(rec,sent,len)
rec[len] = 0;