通过使用指针函数包含更改地址 [英] Changing address contained by pointer using function

查看:111
本文介绍了通过使用指针函数包含更改地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我宣布一个指针 P 为int * P ;一个; ,其中<$ C主模块中,我可以通过指定 P =&放大器改变由 P 包含地址$ C> A 是另一个整数变量已经声明。
我现在想用一个函数为::更改IP地址

If I've declared a pointer p as int *p; in main module, I can change the address contained by p by assigning p=&a; where a is another integer variable already declared. I now want to change the address by using a function as::

void change_adrs(int*q)
{
    int *newad;
    q=newad;
}

如果我把从主模块此功能

If I call this function from main module

int main()
{
    int *p;
    int a=0;
    p=&a; // this changes the address contained by pointer p
    printf("\n The address is %u ",p);
    change_adrs(p);
    printf("\n the address is %u ",p); // but this doesn't change the address
    return 0;
}

地址的内容保持不变。有什么不对使用功能相同的任务?

the address content is unchanged. What's wrong with using a function for same task?

推荐答案

在C,函数的参数是按值传递。因此,一个副本由你的论点和变化到副本,而不是你希望看到修改了实际的指针进行。你需要改变你的函数接受一个双指针参数并进行更改为取消引用的说法,如果你想这样做。
例如:

In C, functions arguments are passed by value. Thus a copy is made of your argument and the change is made to that copy, not the actual pointer that you are expecting to see modified. You will need to change your function to accept a double pointer argument and make the change to the dereferenced argument if you want to do this. For example

 void foo(int** p) {
      *p = 0;  /* set pointer to null */
 }
 void foo2(int* p) {
      p = 0;  /* makes copy of p and copy is set to null*/
 }

 int main() {
     int* k;
     foo2(k);   /* k unchanged */
     foo(&k);   /* NOW k == 0 */
 }

如果您在使用C ++的另一种方式是改变函数接受一个指针引用的奢侈品。

If you have the luxury of using C++ an alternative way would be to change the function to accept a reference to a pointer.

这篇关于通过使用指针函数包含更改地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆