如何将缓冲区复制到C中的字符指针
所以我有一个固定大小的字符数组:如何将缓冲区复制到C中的字符指针,c,arrays,pointers,character,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
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
的第一个参数是目标,第二个参数是源(与strcpy
和strcat
的顺序相同),第三个参数是要复制的字节数。这是非常不完整的!密码在哪里?您需要显示ptr
指向的内容!同样重要的是,buff
的内容是什么?@BryanChen如果ptr
指向有效内存并且buff
是一个nul
终止序列,这就是为什么我说这个问题缺少很多内容。所以我使用buff来读取来自套接字的数据。atm我有char*ptr=malloc(0)。我想在数据进入时重新锁定ptr,并将数据从buff复制到ptr。这有意义吗?是的。如果不进一步定义“部分或全部填充”,就不可能有安全的答案。