Rad'Val
Rad'Val

Reputation: 9231

Read double from void * buffer

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 *

Upvotes: 0

Views: 1143

Answers (3)

masoud
masoud

Reputation: 56509

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];

Upvotes: 1

undur_gongor
undur_gongor

Reputation: 15954

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];

Upvotes: 4

pmg
pmg

Reputation: 108978

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];

Upvotes: 3

Related Questions