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

StackOverflow https://stackoverflow.com/questions/19496826

  •  01-07-2022
  •  | 
  •  

Question

I know the c always pass by values, but if I have a pointer:

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

then I have a function, how to pass pointer p to it and change the value of variable i?

void changeValue(int *p)
{
}

how to pass the pointer and change the variable pointed by p?

Was it helpful?

Solution

This simple example shows how to pass a pointer (i.e. not a value) and recieve back through that pointer, the new value held by the integer. Note the reduced number of variables. i.e. there is no need necessarily to create a separate copy of int *p;. Nor is it necessary in this case to initialize p: p = &i; to the address of 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;  
}

If you do want to create a pointer in the first place, and pass that pointer, then:

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;  
}

It is important to note that your statement: I know the c always pass by values is not correct. It is more common for functions to be written such that pointers are passed because often a pointer is smaller, and more efficient to pass around than the actual variable, especially when large arrays, or structs are used. Keep in mind though that passing &i (the address of i) works just as well as passing p if passing a pointer is called for.

OTHER TIPS

Simply pass it by calling changeValue as

changeValue(p);  

and change the value of variable pointed by it (i) by assigning a value to the *p in changeValue()

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  i = 4;
int * p = &i;
changeValue(p);
printf("%d",*p);

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

Full program - http://ideone.com/DCvhxE

If you dereference the pointer in changeValue and assign to it, it will alter the value of i in the calling frame.

e.g.:

void changeValue(int *p)
{
    *p = 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top