gpt4 book ai didi

c - C语言中如何将缓冲区复制到字符指针

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

所以我有一个固定大小的字符数组:

char buff[100];

我有一个字符指针:

char *ptr;

现在,缓冲区将被部分或全部填充。我想将缓冲区的内容复制到 ptr。我该怎么做?

谢谢

更新:

int rcd; // Received bytes
int temp = 0; // This is used as a size to realloc the dataReceived character pointer
int packetLength = 0; // This is the total packet length
int *client = (int*) data;
int cli = *client; // The client socket descriptor
char buff[100]; // Buffer holding received data
char *dataReceived = malloc(0);

while ((rcd = recv(cli, buff, 100, MSG_DONTWAIT)) > 0)
{
dataReceived = realloc(dataReceived, rcd + temp + 1); // Realloc to fit the size of received data
strcat(dataReceived, buff); // Concat the received buffer to dataReceived
temp = rcd;
packetLength = packetLength + rcd;
memset(buff, 0, 100); // Reinitialize the buffer for the next iteration
}

最佳答案

要将 buffer 的内容复制到 ptr 指向的位置,请使用:

memcpy(ptr, buffer, sizeof(buffer));

memcpy 的第一个参数是目标,第二个是源(与 strcpystrcat 的顺序相同),第三个是要复制的字节数。

关于c - C语言中如何将缓冲区复制到字符指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33663296/

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