如何将byte []复制到char*中?

Iva*_*nov 0 c c++

我需要的只是strcpy().

我想看看缓冲区(字节数组)的前三个字节是否为"JMX"字符串.

这是我到目前为止所做的:

char * ddj;
strcpy( ddj, buffer ); //buffer is BYTE[]
if ( strcmp( "JMX", ddj ) == 0 ) //check first three chars are "JMX"
{
    buffer += 20;   //increase the index with 20
    size -= 20;     //int
}
Run Code Online (Sandbox Code Playgroud)

我在strcmp()行遇到异常.问题是什么?

我希望我用C#写这个:(

Ste*_*202 8

这里出了问题:

  1. ddj不指向任何实际的记忆.因此,副本将具有未定义的行为
  2. 首先不需要复制.

这是你可以做的:

if(strncmp("JMX", buffer, 3) == 0) {
  buffer += 20;
  size -= 20;
}
Run Code Online (Sandbox Code Playgroud)

这使用strncmp而不是strcmp,从而确保比较不超过三个字节.如果buffer可以包含少于三个字节,您应该执行以下操作:

if(buf_len >= 3 && strncmp("JMX", buffer, 3) == 0) {
  buffer += 20;
  size -= 20;
}
Run Code Online (Sandbox Code Playgroud)


Ada*_*eld 6

你没有分配任何内存ddj.因为它是一个局部变量,所以它被分配在堆栈中.默认情况下,局部变量不会初始化为0/false/NULL,因此ddj声明之后的值是未定义的 - 它将具有堆栈中该特定位置的内存中剩余的值.任何取消引用它的尝试(即,读取或写入它指向的内存)都将具有未定义的行为.在你的情况下,它崩溃,因为它指向一个无效的地址.

要解决此问题,您需要为其分配存储空间ddj.您可以在堆栈上分配静态存储,也可以在堆上分配动态存储.要分配静态存储,请执行:

// Allocate 64 bytes for ddj.  It will automatically be deallocated when the function
// returns.  Be careful of buffer overflows!
char ddj[64];
Run Code Online (Sandbox Code Playgroud)

分配动态存储:

// Allocate 64 bytes for ddj.  It will NOT be automatically deallocated -- you must
// explicitly deallocate it yourself at some point in the future when you're done
// with it.  Be careful of buffer overflows!
char *ddj = new char[64];
...
delete [] ddj;  // Deallocate it
Run Code Online (Sandbox Code Playgroud)

而不是自己管理存储,使用它会更好,它会std::string自动处理内存管理.

最后,由于您所做的只是比较字符串的前三个字符,因此无需跳过箍来复制字符串并进行比较.只需使用strncmp():

if(strncmp(buffer, "JMX", 3) == 0)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)