gpt4 book ai didi

将char数组的一部分复制到c中的字符串

转载 作者:行者123 更新时间:2023-12-04 06:24:33 26 4
gpt4 key购买 nike

我已经阅读了许多建议的问题,但仍然找不到答案。我知道缓冲区中的内容是以 NULL 结尾的 char array ,我想把它复制到一个动态分配的 char array .但是,我不断收到来自 strcpy 的段错误。功能。谢谢你的帮助。

void myFunction()
{
char buffer[200];

// buffer was filled by recvfrom correctly, and can be printed out with printf()
char *message = malloc(200);

strcpy(message, buffer[1]);
}

///////////////

好的,所以我尝试了 strcpy(message, &buffer[1]); strcpy(message, buffer);但没有任何效果!!

最佳答案

您对 strcpy(3) 的调用是不正确的。将其更改为以下内容:

    buffer[199] = '\0';
strcpy(message, &buffer[1]);
strcpy(3)具有以下签名:
 char *
stpcpy(char *s1, const char *s2);

你传入了:
 char *stpcpy(char *s1, const char s2); /* won't work */

我建议使用 memcpy(3)而不是 strcpy(3)strcpy(3)依赖空字符来终止字符串。

关于将char数组的一部分复制到c中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6194424/

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