The function returns an array of BYTE

I want my function to return a BYTE array. The function is as follows.

BYTE sendRecieveData(BYTE control, unsigned int value){

//Open connection to LAC
HANDLE LACOutpipe;
HANDLE LACInpipe;
LACOutpipe=openConnection(MP_WRITE);
LACInpipe=openConnection(MP_READ);

//declare variables
BYTE bufDataOut[3];
BYTE bufDataIn[3];
DWORD bufInProcess;
DWORD bufOutProcess;


//sets CONTROL
bufDataOut[0]=control;

//sets DATA to be sent to LAC
BYTE low_byte = 0xff & value;
BYTE high_byte = value >> 8;
bufDataOut[1]=low_byte;
bufDataOut[2]=high_byte;

MPUSBWrite(LACOutpipe,bufDataOut,3,&bufOutProcess,1000);
MPUSBRead(LACInpipe,bufDataIn,3,&bufInProcess,1000);
MPUSBClose(LACOutpipe);
MPUSBClose(LACInpipe);

return bufDataIn[3];
}

It does not return an array of bytes, and when I change BYTEto BYTE[]or BYTE[3], it gives me an error.

+5
source share
2 answers

return bufDataIn[3];means "return the 4th element of the array bufDataIn", and in this case it leads to undefined behavior, since the size of this array is 3.

You can allocate memory for this new array in the body of your function and return a pointer to your first element:

BYTE* createArray(...)
{
    BYTE* bufDataOut = new BYTE[3];
    ....
    return bufDataOut;
}

Do not forget deletewhen you are done with it:

{
    BYTE* myArray = createArray(...);
    ...
    delete[] myArray;
}

, std::vector<BYTE> ;) , , .

+9

, .

void sendRecieveData(BYTE control, unsigned int value, BYTE (&buffdataIn)[3] ).

:

BYTE result[3] = {0};
sendRecieveData(3, 0, result);

, .

+3

All Articles