-2

我需要将一个无符号字符数组从一种方法传递给另一种方法,我尝试使用以下代码:

{
     unsigned char *lpBuffer = new unsigned char[182];
 ReceiveSystemState(lpBuffer);

}

BOOL ReceiveSystemState(unsigned char *lpBuffer)
  {
      unsigned char strRecvBuffer[182] = { 0 };
      //strRecvBuffer construction

      memcpy(lpBuffer, strRecvBuffer, sizeof(strRecvBuffer));

      return TRUE;
 }

这 3 种方法(在 中使用ReceiveSystemState)都没有按我的预期工作。在使用它们中的每一个之后,它被复制的只是第一个字符strRecvBuffer,仅此而已。从strRecvBuffer元素到元素都有空字符,但我需要它们,因为该字符串是来自硬件设备的消息,并且该消息将使用协议进行分析。我在这里想念什么?我初始化lpBuffer错误吗?

编辑:我使用了一种简单的memcpy方法来完成这项工作。结果还是一样:它被复制的只是strRecvBuffer.

EDIT2:工作代码:

{
     unsigned char *lpBuffer = new unsigned char[182];
     ReceiveSystemState(lpBuffer);
     for (int i = 0; i < 144; i++)
     {
         memcpy(&c_dateKG[i], lpBuffer + i * sizeof(unsigned char), sizeof(unsigned char) );
     }

}    
  BOOL ReceiveSystemState(unsigned char *lpBuffer)
  {
     unsigned char strRecvBuffer[182] = { 0 };
     //strRecvBuffer construction

     memcpy(lpBuffer, strRecvBuffer, sizeof(strRecvBuffer));

     return TRUE;
  }
4

1 回答 1

7

你的代码绝对是垃圾。一些注意事项:

使用sizeof

使用sizeof(static_massive_name);count_of_arr_elements * sizeof(arr_type);

例如:

unsigned char src[255];    
unsigned char dst[255];

// fill src with random data
for (int i = 0; i < 255; ++i) {
    src[i] = static_cast<unsigned char> (rand() % 255);
}

memcpy(dst, src, sizeof(dst));


// now dst will have copied values from src (random numbers)

更新

完整的测试源代码:

#include <iostream>
#include <string.h>
#include <time.h>
#include <stdlib.h>

using namespace std;

void print(unsigned char* arr, size_t size) {
    for (size_t i = 0; i < size; ++i) { 
        // see type casting (to int)!!!
        cout << "arr[" << i << "] = " << (int)arr[i]<< endl;
    }
}

int main() {
    srand(time(0));

    // unsigned char type hold values from 0 to 255
    unsigned char src[15];
    unsigned char dst[15];

    for (int i = 0; i < 15; ++i) {
        src[i] = rand() % 255;
    }

    memcpy(dst, src, sizeof(dst));

    print(src, 15);
    print(dst, 15);

    return 0;
}

结果:

arr[0] = 34
arr[1] = 80
arr[2] = 183
arr[3] = 112
arr[4] = 18
arr[5] = 120
arr[6] = 183
arr[7] = 0
arr[8] = 0
arr[9] = 0
arr[10] = 0
arr[11] = 57
arr[12] = 137
arr[13] = 4
arr[14] = 8
arr[0] = 34
arr[1] = 80
arr[2] = 183
arr[3] = 112
arr[4] = 18
arr[5] = 120
arr[6] = 183
arr[7] = 0
arr[8] = 0
arr[9] = 0
arr[10] = 0
arr[11] = 57
arr[12] = 137
arr[13] = 4
arr[14] = 8
于 2012-10-05T07:52:06.827 回答