Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to c. I am considering that value of i should be changed but actually it didnt.

In f function:
C
void f(int *p, int a) {
    p = &a;
}


In main function:
C
int main() {
    int i = 10, j = 20;
    change(&i, j);
    printf("%d", i);
    return 0;
}


Why is value of i still 10even after i passed pointer variable as argument. Why is it still behaving as pass by value.

What I have tried:

Its getting out of head please help. I am having hard time understanding it.
Posted
Updated 22-Dec-22 4:17am
v3

1 solution

Simple: you don't call f at all in that code.
You call a function called change - but we don't have source code for that and it's very likely that your code doesn't compile. If it doesn't compile, no EXE file is produced, so any EXE you execute doesn;t reflect the latest changes to your source code.

Even if you did, you don't change what p points to: you set a new value for the local parameter variable p which isn't reflected in the "outside world" because in C all parameters are passed by value: a copy is made of the value you pass rather than any actual variable.

Try this:
C
#include <stdio.h>
void f(int *p, int a) {
    *p = a;
}

int main() {
    int i = 10, j = 20;
    f(&i, j);
    printf("%d", i);
    return 0;
}
Now you pass the address of i to the function and alter the value of the variable it points to, so the result printed changes.
 
Share this answer
 
Comments
CPallini 22-Dec-22 10:25am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900