繁体   English   中英

如何将指针传递给函数并将值分配给C中指向的变量?

[英]how to pass the pointer to a function and assign the value to the variable pointed to in C?

我知道c总是通过值传递,但是如果我有一个指针:

int  i = 4;
int * p;
p = &i;

然后我有一个函数,如何将指针p传递给它并更改变量i的值?

void changeValue(int *p)
{
}

如何传递指针并更改p指向的变量?

只需通过将changeValue调用为

changeValue(p);  

并通过为changeValue()*p赋值来更改它所指向的变量( i )的值

void changeValue(int *p)  
{
     *p = an int value;
}
void changeValue( int* ) ;

int main( void )
{
    int  i = 4; // Suppose i is stored at address 1000h
    int * p;    
    p = &i;     // Now p stores the address of i that is 1000h

    changeValue(p); // Can also be written as changeValue(&i);
    // Here you are passing the address of i to changeValue function

    return 0 ;
}

void changeValue( int* p ) // Accept a parameter of type int*
{
    *p = 100 ; // store the value 100 at address 1000h
    return ;
}

这个简单的示例说明了如何传递指针(即不是值)并通过该指针接收返回的值,该新值由整数保存。 注意减少的变量数量。 也就是说,没有必要创建int *p;的单独副本int *p; 在这种情况下也不必初始化p: p = &i; 到i的地址。

int changeValue(int *);
int main(void)
{
    int i=15;
    changeValue(&i);
    return 0;
}

int changeValue(int *p) //prototyped to accept int *
{
    return *p = 3;  
}

如果确实要首先创建一个指针并传递该指针,则:

int changeValue(int *);
int main(void)
{
    int i=15;
    int *p;
    p = &i;
    *p; // *p == 15 at this point
    //since p is already a pointer, just pass
    //it as is
    changeValue(p);
    return 0;
}

int changeValue(int *q) //prototyped to accept int *
{
    return *q = 3;  
}

重要的是要注意您的声明: I know the c always pass by values是不正确的。 编写函数以传递指针的情况更为常见,因为指针通常比实际变量更小并且传递效率更高,尤其是在使用大型数组或结构时。 请记住,尽管如果需要传递指针,则传递&i&i的地址)与传递p一样有效。

int  i = 4;
int * p = &i;
changeValue(p);
printf("%d",*p);

void changeValue(int *p)
{
    *p = 5;
}

完整程序-http://ideone.com/DCvhxE

如果取消引用changeValue的指针并将其分配给指针,它将更改调用帧中i的值。

例如:

void changeValue(int *p)
{
    *p = 0;
}

暂无
暂无

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

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