简体   繁体   English

我正在尝试对 C++ 中的两个指针的值进行算术运算,但它有时有效,有时失败。 努力在网上寻找解释

[英]I'm Trying to do Arithmetic on the Value of Two Pointers in C++ but it Sometimes Works and Sometimes Fails. Struggling to Find Explanations Online

I feel silly due to the basicness of the question but using my basic understanding of pointers my program is performing unexpectedly and I can't understand why.由于问题的基本性,我感到很傻,但是使用我对指针的基本理解,我的程序意外地执行了,我不明白为什么。

#include <stdio.h>

void update(int *a,int *b) {
    
    *a = *b + *a;
    *b = (*a - *b);
}

int main() {

    int a, b;
    int *pa = &a, *pb = &b;
    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);
    return 0;
}

So, pointers point to a memory address.因此,指针指向 memory 地址。 If I would do arithmetic on the pointer itself I would change the address location.如果我要对指针本身进行算术运算,我会更改地址位置。 But a *(pointer variable) would be the value at the memory address.但是 *(指针变量)将是 memory 地址处的值。 Is it wrong to assume that arithmetic such as (*a + *b) = *a works basically the same as (a + b) = a.假设 (*a + *b) = *a 之类的算术与 (a + b) = a 的工作原理基本相同,这是错误的吗? I assumed I was correct due to *a = (*b + *a) working as I intended in my code.我认为我是正确的,因为 *a = (*b + *a) 按照我在代码中的预期工作。

So I'm quite confused as *b = (*a - *b) seemingly always changes *b = *a rather than actual subtraction.所以我很困惑,因为 *b = (*a - *b) 似乎总是改变 *b = *a 而不是实际的减法。 With inputs of 5 and 2 making *b = 5 which wouldn't make sense if subtraction took place.输入 5 和 2 使 *b = 5 如果发生减法,这将没有意义。 Input: 6,5 Outputs: 6 Input: 2, 1 Outputs: 2输入:6,5 输出:6 输入:2, 1 输出:2

Also, I have tested the code in hacker rank and visual studio code and I keep getting the same result for *b in both.此外,我已经在黑客等级和 Visual Studio 代码中测试了代码,并且我在两者中都得到了相同的 *b 结果。 The top search results for "arithmetic on pointer values", "how to change value at a memory address c++" and "can you do math on the value of pointers c++" either don't address my question (though they could be address my question but I just didn't make the connection.) “指针值的算术运算”、“如何在 memory 地址 c++ 上更改值”和“你能对指针 c++ 的值进行数学运算”的热门搜索结果要么不能解决我的问题(尽管它们可以解决我的问题)问题,但我只是没有建立联系。)

If someone could explain why I'm getting the output for *b that was unexpected, if doing arithmetic on *b and *a actually works the way I think it should and if there is a better or more efficient way to do what I'm trying to accomplish.如果有人可以解释为什么我会为 *b 得到 output,这是出乎意料的,如果对 *b 和 *a 进行算术运算实际上按我认为应该的方式工作,以及是否有更好或更有效的方法来做我想做的事情'我试图完成。 I truly appreciate anyone who answers.我真的很感谢任何回答的人。 Thanks谢谢

This has nothing to do with them being pointers, but with the operations being done.这与它们是指针无关,而是与正在完成的操作有关。

*a = *b + *a;
*b = (*a - *b);

is done in sequence, so the *a value is changed before calculating *b .是按顺序完成的,因此在计算*b之前会更改*a值。
I assume you were expecting something like我假设你期待类似的东西

int a_before = *a;
*a = *b + *a;
*b = (a_before - *b);

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

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