Search code examples
cpointersprogramming-languagestype-conversion

C Language - [copy in place] float* to char* and the reverse


I want to copy a float buffer into a char (byte) buffer without allocating memory for two separate buffers. In another words I want to use one buffer and copy in place. The Problem is that if I need a float buffer then in order to copy that to a char then I will need a char* pointer; If I were copying from float* to float* it would be easy as I would just pass in the same pointer for the target and the source.

eg.

void CopyInPlace(float* tar, float* src, int len) {
....
}
CopyInPlace(someBuffer, someBuffer, 2048);

void PackFloatToChar(char* tar, float* src, int len) {

}
????????

How would I do this?

Does memcpy copy in place?, if passed in the same pointer?


Solution

  • Your question seems a bit confused.

    Do you want to simply interpret an array of floats as a char array (for something like writing to a file?). If so, simply cast. All pointers in C can be represented by char*'s.

    memcpy will copy from one memory location to another. But keep careful track of whether your "len" parameter is the number of floats or number of bytes. If "len" is the count of floats in the array, multiply it by sizeof(float) in the memcpy call.