简体   繁体   English

C ++指针解引用乘法

[英]C++ Pointer Dereference Multiplication

I am currently programming an arduino and am using C++ objects to do so. 我目前正在编程arduino,并且正在使用C ++对象来这样做。 I've run into a weird issue when I try to multiply the values that are being pointed at. 当我尝试乘以所指向的值时,我遇到了一个奇怪的问题。 Referring to the code below, when I run the program, var3 and var4 end up having two different values. 参考下面的代码,当我运行程序时,var3和var4最终具有两个不同的值。 Why is this? 为什么是这样? They are essentially multiplying the same values (or so I believe). 它们本质上是在乘以相同的值(或者我相信)。 Any help? 有什么帮助吗?

 long var1 = info->accelXYZ[0];
 long var2 = info->taughtAccelXYZ[0];
 long var3 = var1*var2;

 long var4 = info->accelXYZ[0]*info->taughtAccelXYZ[0];

It's possible you're overflowing in one of the situations. 您有可能在其中一种情况下溢出。

The multiplication of var1 and var2 (both long ) gives a long which is then loaded into var3 . var1var2的乘积(均为long )给出一个long ,然后将其加载到var3

If both info->accelXYZ[0] and info->taughtAccelXYZ[0] are int (for example), the result of the multiplication will be int which is then loaded into a long . 例如,如果info->accelXYZ[0]info->taughtAccelXYZ[0]均为int ,则乘法结果将为int ,然后将其装入long

The intermediate int form may be overflowing, something you can see in the following snippet: 中间int形式可能溢出,您可以在以下代码段中看到这些内容:

#include <stdio.h>
#include <limits.h>

int main(void) {
    printf("int has %d bytes\n",sizeof(int));
    printf("long has %d bytes\n",sizeof(long));

    int a = INT_MAX;
    int b = 2;

    long var1 = a;
    long var2 = b;

    long var3 = a * b;
    long var4 = var1 * var2;

    printf ("var3=%ld\n", var3);
    printf ("var4=%ld\n", var4);

    return 0;
}

which outputs: 输出:

int has 4 bytes
long has 8 bytes
var3=-2
var4=4294967294

One reason why var3 may end up with a different value than var4 is integer overflow . var3最终值可能不同于var4一个原因是整数溢出 This happens when both multiplicands fit in an int , but the product doesn't. 当两个被乘数都适合int ,但乘积不适合时,就会发生这种情况。

Since int s and long s have different sizes on Arduino Uno * , the computation of var3 is different from computation of var4 . 由于intlong在Arduino Uno *上具有不同的大小,因此var3计算与var4计算不同。

When you compute var3 , the multiplication is done in long s on the initial values that fit in an int , so the result of multiplication is not translated. 当您计算var3 ,会在long对适合int的初始值进行乘法运算,因此不会转换乘法结果。 When you compute var4 , the computation is done in int s, and then promoted to long . 当您计算var4 ,计算以int s完成,然后提升为long However, by then the result is already truncated, which results in the discrepancy that you are observing. 但是,到那时结果已被截断,这导致您正在观察到差异。

To make var4 the same correct value as var3 , add a cast to long to one of the multiplicands, like this: 为了使var4同样正确的值作为var3 ,铸造加long到被乘数之一,就像这样:

long var4 = (info->accelXYZ[0])*((long)info->taughtAccelXYZ[0]);

* int has 16 bits, while long has 32 bits. * int有16位,而long有32位。

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

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