我需要将unsigned char数组从一个方法传递给另一个方法,我尝试使用此代码:
{
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;
}
这三种方法(在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;
}
答案 0 :(得分:6)
你的代码绝对垃圾。一些说明:
使用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(src, dst, sizeof(dst));
// now dst will have copyed 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(src, dst, 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