gpt4 book ai didi

c - 如何将某些字符从一个字符串传输到另一个字符串?

转载 作者:行者123 更新时间:2023-11-30 14:39:25 25 4
gpt4 key购买 nike

我想将一些字符从一个字符串保存到另一个字符串。

我尝试从一个字符串中逐个字符并将它们保存到另一个字符串中。

#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);
}

如果我输入“Hello world”,预期输出应该是“Hel”,但它是“Hel”和一些随机字符。而且我也不明白为什么rec的长度等于14。

最佳答案

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

或更一般的

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

关于c - 如何将某些字符从一个字符串传输到另一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com