改变C函数中指向的内容

时间:2012-02-15 21:30:28

标签: c

如何让这个函数改变x指向的内容:

void test(const int *x)

4 个答案:

答案 0 :(得分:3)

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函数的原型。

答案 1 :(得分:1)

这是指向const int的指针。您无法使用它来更改它指向的值。

答案 2 :(得分:1)

void test(const int *x)

此处的const指定不允许该函数修改指针。如果你想修改指针,请按以下方式声明你的函数:

void test(int *x)

当然,如果您的意思是希望x指向不同的对象,那么您只需在函数体中指定x即可。但这听起来不太可能是你想做的事。

答案 3 :(得分:0)

我没有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);
}