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

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

问题描述

如果我已经声明一个指针 pint *p;在主模块中,我可以通过分配 p=&a; 来更改 p 包含的地址,其中 a 是另一个已经声明的整数变量.我现在想通过使用一个函数来更改地址::

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("
 The address is %u ",p);
    change_adrs(p);
    printf("
 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 object that you are expecting to see modified. You will need to change your function to accept a pointer-to-pointer argument and make the change to the dereferenced argument if you want to do this. For example

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

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

如果您有幸使用 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天全站免登陆