开发者

Read double from void * buffer

开发者 https://www.devze.com 2023-04-12 07:47 出处:网络
Please excuse my lack of understanding, I\'m a beginner with C. So, I have a void * buffer that开发者_开发问答 I calloc like this:

Please excuse my lack of understanding, I'm a beginner with C. So, I have a void * buffer that开发者_开发问答 I calloc like this:

void * dataBuffer = calloc(samples, sizeof(double));

and would like to later read it like this:

double myDoubleDB = dataBuffer[sampleIndex];

but I get an error because they are of different types (void and double).

How can I achieve this? My arch is ARM and I'm using GCC to compile

UPDATE: dataBuffer is out of my reach (other library) and it simply comes as void *


double *dataBuffer = calloc(samples, sizeof(double));

Note that 2 bytes will probably not be enough for a double.

Note also that all bits 0 in memory (as provided by calloc) do not necessarily represent a valid double value (on most platforms, it will, see IEEE754).

If you cannot change the declaration of dataBuffer, you should still correct the calloc and then cast (as proposed by others):

double myDoubleDB = ((double*)dataBuffer)[sampleIndex];


If you can make it a pointer to double in the first place, so much the better.

double * dataBuffer = calloc(samples, sizeof *dataBuffer);
double myDoubleDB = dataBuffer[sampleIndex];

Otherwise, just unsafely explicitly convert the void* to double* with a cast:

void * dataBuffer = calloc(samples, sizeof (double));
double myDoubleDB = ((double*)dataBuffer)[sampleIndex];


You need some casting :

double myDoubleDB = ((double*)dataBuffer)[sampleIndex];

Note: it is better use pointer to double instead of void for simplicity.

According to new update:

You can use a pointer to reduce castings:

double *doubleDataBuffer = (double*) dataBuffer;
double myDoubleDB = doubleDataBuffer[sampleIndex];
0

精彩评论

暂无评论...
验证码 换一张
取 消