简体   繁体   English

将数组传递给 function 而不是变量

[英]Pass array to a function instead of variable

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.我只想创建一个 function 它将数组作为输入而不是双精度。 Why are the following two code segments not the same, not even for j == 0?为什么以下两个代码段不一样,甚至对于 j == 0 也不一样? (I get different values when printing *buf ) (打印*buf时我得到不同的值)

1.) 1.)

void
SVPublisher_ASDU_setFLOAT64(SVPublisher_ASDU self, int index, double value)
{
    uint8_t* buf = (uint8_t*) &value;

print:打印:

valueArray value: 1.145000

2.) 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 uint8_t 是无符号字符

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.buf设置为value的地址,这是一个参数,这意味着它是传递的参数的副本。 The compiler has put that copy somewhere, so buf gets the address of that location.编译器已将该副本放在某处,因此buf获取该位置的地址。 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.buf设置为从valueArray计算的地址,该地址是传递给它的地址,并且该地址是调用者的某个数组(或单个对象)的开始。 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);此外, (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 .由于valueArray是一个指向double的指针,所以+ 8 * j的地址算术以double为单位工作,因此valueArray + 8 * j是 memory 中的一个位置,它从valueArray位移了8 * j类型的double对象的大小。 The later cast to (uint8_t *) does not affect this;稍后转换为(uint8_t *)不会影响这一点; 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.您可能需要(uint8_t *) (valueArray + j)在这里,但不清楚您要完成什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM