如何将缓冲区复制到C中的字符指针

时间:2015-11-12 02:12:37

标签: c arrays pointers character

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

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
}

1 个答案:

答案 0 :(得分:1)

要将buffer的内容复制到ptr指向的任何地方,请使用:

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

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