【解決方法】変数の値ではなくアドレスが増えるのはなぜですか?


*p++ のような式でポインターの値が変化する理由を知識のある人が説明してくれれば幸いです。

#include <stdio.h>

int main(void) {
    int a=1,*p;
    p=&a;
    printf("The original Addres is:%p and a is %d\n",p,a);
    a=(*p)++;
    printf ("The second Address is %p and a is %d",p,a);
}

私が試したこと:

*p++ でも。 変数の値ではなく、ポインターの値が変更されます。

解決策 1

あなたが投稿したコードで p 一定のまま。

C++
a = (*p)++;

その理由は、上記のステートメントが次のように述べているからです。
– に格納されている値を取得します p そしてそれを1ずつ増やします
– 次に、結果の値を変数に保存します a

この場合、値 pのアドレスは変わりません。

コードを次のように変更した場合:

C++
a = *p++;

それから p 増えますが、 a このステートメントが言うように、しません:
– に格納されている値を取得します p そしてそれを変数にコピーします a

– 次に、のアドレスをインクリメントします p

解決策 2

ここでは 2 つのことが行われています。 1 つ目は演算子の優先順位で、2 つ目は演算子の優先順位です。 役職インクリメント。

 // the expression:
a = *p++;
// is equivalent to
a = *p;  // dereference p 
p += 1;  // increment p after access
         // Note that now dereferncing p invokes undefined behavior

// If you want to increment what p is pointing to without moving it then you want
a = ++(*p);
// Note that as the source and destination are the same address, I think it is undefined as
// to what gets assigned to a.  It's much better in this case to do
a = *p + 1;
// as that will not invoke undefined behavior.

コメント

タイトルとURLをコピーしました