繁体   English   中英

更改C函数中指向的内容

[英]Changing what is being pointed to in a C function

我如何获得此函数来更改x指向以下内容:

void test(const int *x)
void test(const int *x)
{
    *((int *) x) = 42;
}

但是,如果您指向的对象是const ,则将调用未定义的行为,例如:

const int bla = 58;
test(&bla);   // undefined behavior when the function is executed

还行吧:

int blop = 67;
test(&blop);

如果要修改所指向的对象,则宁愿更改test功能的原型。

它是const int的指针。 您不能使用它来更改它指向的值。

void test(const int *x)

此处的const指定不允许该函数修改指针。 如果要修改指针,请声明您的函数,如下所示:

void test(int *x)

当然,如果您要让x指向另一个对象,则只需在函数体内将x赋值即可。 但这听起来并不是您想要的。

我没有C编译器,但是此C ++应该可以正常工作:

void test(const int **x)
{
    static const int newx = 123;
    *x = &newx;
}

int main()
{
    const int Temp = 999;

    const int* y = &Temp; 

    test(&y);
}

暂无
暂无

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

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