If you're not planning to change that copy anywhere (i.e., if you're using it for read-only purposes), then here is a simple solution for you, with a time complexity of O(0):
char* pDataBuffer = (char*)&iData;
Of course, if iData
is a local variable, then you cannot use the value of this pointer outside the function.
Also, please note that pDataBuffer[i]
will be interpreted differently on different Endian architectures.
If you need a copy of it for write purposes, then you can simply use function memcpy
as follows:
char* pDataBuffer = malloc(sizeof(iData));
memcpy(pDataBuffer,&iData,sizeof(iData);
return pDataBuffer;
If possible, then I strongly recommend that you allocate it statically outside the function, and pass as needed.
For example:
void SomeFunction()
{
...
char aDataBuffer[sizeof(iData)];
SomeOtherFunction(aDataBuffer);
...
}
void SomeOtherFunction(char* pDataBuffer)
{
...
memcpy(pDataBuffer,&iData,sizeof(iData);
...
}
Otherwise, you'll need to free
the allocated memory at some later point in the execution of your program.
Again, keep in mind that pDataBuffer[i]
will be interpreted differently on different Endian architectures.