更改指针指向的地址

时间:2017-08-15 11:58:01

标签: c++ c++11 pointers

我想更改不同的指针(不同类型),它们指向NULL / 0 / nullptr ...,但我必须使用变量来执行此操作!
一般来说,我理解指针,我知道问题是什么,但我不知道如何解决它。

所以我需要像

这样的东西
int NULLPOINTER = nullptr;                 // data type can change if needed
int* myIntPointer = NULLPOINTER;
float* myFloatPointer = NULLPOINTER;
foo* myFooPointer = NULLPOINTER;

如上所示,由于无效的转换错误(int to int * / float * / foo *),这是不可能的。

那我该如何归档呢? 根据要求提供了一个更复杂的澄清示例:

class foo
{
    float floatVar;
};

class bar
{
    char charVar;
};

void changeSomething(bar* pBarTmp)
{
    /* pGlobal is a member of another class and the type is depends on the method */
    pGlobal = pBarTmp;
}

int main()
{
    /* Working just fine */
    int var = 1;
    int *pointer  = &var;

    /* Also working fine */
    foo *pointer = 0;    //nullptr or NULL or __null (compiler dependend)

    /* Not working because newAddress is int and not bar* / foo* / int* */
    int newAddress = 0;

    // Only one of the following is present, it depends on the 
    // method/class (just for visualization) 
    bar *pointer = newAddress;               
    foo *pointer = newAddress;
    int *pointer = newAddress;

    changeSomething (pointer);
}

我不能将int newAddress;更改为int* newAddress;
总的来说,我不会使用除NULL / 0 / nullptr / ...

以外的其他东西

另一个困难是,我不能使用reinterpret_cast编码指南的原因。

4 个答案:

答案 0 :(得分:4)

  

int* p3 = 1; //Error invalid conversion from int to int

您可以直接在C ++中设置指针的地址

int* p3 = reinterpret_cast<int*>( 0x00000001 );

但它不是一个好主意,因为你不知道指针指向内存和去引用会导致未定义的行为。

无效转换,因为1的类型为int,如果没有强制转换,则无法分配给指针变量int *

  

int* p2 = 0; //p is a NULL-pointer

应该初始化指向null的指针

int* p2 = nullptr;

而不是

int* p2 = 0;

C++11开始,您可以创建std::nullptr_t的实例并将其分配给指针。

std::nullptr_t initAddr;
int* p2 = initAddr;

答案 1 :(得分:2)

  

更改地址指针指向

     

我的目标是将不同指针类型的地址更改为NULL

通过作业:

int* p = nullptr;
  

我必须使用变量来执行此操作。

int newAdress = 0;
int* p2 = newAdress;

此处的错误是newAdress的类型错误。编译器通过告诉你错误来帮助你。您将需要使用指针(兼容类型)变量来指定指针:

int* newAdress = nullptr;
// ^ see here, a pointer

int* p2 = newAdress;
int* p3 = 1;

在大多数情况下,这项任务毫无意义。 1不为空,通常也不保证该内存位置有int个对象。

尽管如此,在某些特殊情况下您需要特定的地址值。这可以通过铸造来实现:

int* p3 = reinterpret_cast<int*>(1);

如果你不知道这种情况,那么你就不需要这样做了。如果你没有这种情况,那么使用指向任意内存位置的指针有不确定的行为。

答案 2 :(得分:2)

C ++ 11附带nullptrnullptr类型std::nullptr_t。您可以创建此实例并指定:

int* p1;
char* p2;
double* p3;
std::nullptr_t newAddress;
p1 = newAddress;
p2 = newAddress;
p3 = newAddress;

Demo

这满足您在变量中使用NULL

答案 3 :(得分:0)

您必须了解int*int。你不应该直接改变地址。这似乎毫无意义,因为每个程序运行变量都保存在具有不同地址的不同内存部分中。

它仅适用于NULL,它与0相同,但在C ++ 11中应该避免使用nullptr来保证安全。

您可以使用地址操作员&设置地址:

int a;
int* b = &a;
相关问题