Reputation: 75
I have a pretty basic problem, but I really don't understand what's going on.
I just want to create a function which takes an array as input instead of a double. Why are the following two code segments not the same, not even for j == 0? (I get different values when printing *buf)
1.)
void
SVPublisher_ASDU_setFLOAT64(SVPublisher_ASDU self, int index, double value)
{
uint8_t* buf = (uint8_t*) &value;
print:
valueArray value: 1.145000
2.)
void
SVPublisher_ASDU_setFLOAT64Array(SVPublisher_ASDU self, int index, const double* valueArray, int length)
{
for (int j = 0; j < length; ++j) {
uint8_t* buf = (uint8_t*) (valueArray + 8 * j);
print:
valueArray value: 3070733822295138354700875252470016317131267959765042782153548795915832793917922493698408448.000000
uint8_t is unsigned char
Upvotes: 0
Views: 79
Reputation: 222437
uint8_t* buf = (uint8_t*) &value;
sets buf
to the address of value
, which is a parameter, meaning it is a copy of the argument that was passed. The compiler has put that copy somewhere, so buf
gets the address of that location. uint8_t* buf = (uint8_t*) (valueArray + 8 * j);
sets buf
to an address calculated from valueArray
, which is an address passed to it, and that address is the start of some array (or single object) of the caller. There is no reason to expect these to be the same; the address of a parameter in one set of source code is largely unrelated to the address of some array in another set of source code.
Additionally, (uint8_t*) (valueArray + 8 * j);
is not likely the calculation you want. Since valueArray
is a pointer to double
, the address arithmetic with + 8 * j
works in units of double
, so valueArray + 8 * j
is a place in memory that is displaced from valueArray
by the size of 8 * j
objects of type double
. The later cast to (uint8_t *)
does not affect this; it causes a conversion after the arithmetic. You might want (uint8_t *) (valueArray + j)
here, but it is not clear what you are trying to accomplish.
Upvotes: 1