简体   繁体   中英

How do I transfer certain characters from one string to another?

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.

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

or more general

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM