14

アドレスの値をポインターではない int 変数に格納しようとしています。変換しようとすると、「「int*」から「int」への変換が無効です」というコンパイル エラーが表示されます。これは私が使用しているコードです。 :

#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

vector<int> test;

int main() {
    int *ip;
    int pointervalue = 50;
    int thatvalue = 1;

    ip = &pointervalue;
    thatvalue = ip;

    cout << ip << endl;

    test.push_back(thatvalue);

    cout << test[0] << endl;
    return 0;
}
4

6 に答える 6

26

intポインターを格納するのに十分な大きさではない可能性があります。

を使用する必要がありますintptr_t。これは、任意のポインターを保持するのに十分な大きさを明示的に持つ整数型です。

    intptr_t thatvalue = 1;

    // stuff

    thatvalue = reinterpret_cast<intptr_t>(ip);
                // Convert it as a bit pattern.
                // It is valid and converting it back to a pointer is also OK
                // But if you modify it all bets are off (you need to be very careful).
于 2012-12-30T19:33:16.453 に答える
8

あなたはこれを行うことができます:

int a_variable = 0;

int* ptr = &a_variable;

size_t ptrValue = reinterpret_cast<size_t>(ptr);
于 2012-12-30T17:17:37.257 に答える
4

Cコードの場合、とにかくキャストする必要があるのはなぜですか:

thatvalue = (int)ip;

C++ コードを作成する場合は、使用することをお勧めしますreinterpret_cast

于 2012-12-30T17:17:06.710 に答える
4

使用することをお勧めしreinterpret_castます:

thatvalue = reinterpret_cast<intptr_t>(ip);
于 2012-12-30T17:17:37.977 に答える
0

C のユニオン ステートメントを使用して、探していたものを実現できました。もちろんコンパイラに依存しますが、私にとってはうまくいきました(Linux、g ++)。

union {
    int i;
    void *p;
} mix;

mix.p = ip;
cout << mix.i << endl;

私の特定のインスタンスでは、int は 32 ビットで、ポインターは 48 ビットです。ポインターを割り当てる場合、整数値 i はポインターの最下位 32 ビットを表します。

于 2021-02-01T21:57:03.277 に答える