#include <stdio.h>
int value(int *a);
int main(){
int num = 4;
value(&num);
printf("value of number is = %d", num);
return 0;
}
int value(int *a){
int c = (*a)*10;
return c;
}
In this code, I transfer the address in function but it does not change, Why?
>Solution :
You have 2 ways of having a function change data outside it, you can pass a variable by reference and update it or you can return a value and use that. You are mixing half of each method (I reordered the code to make my commentary clearer)
#include <stdio.h>
int value(int *a);
// here you are passing by reference, good
int value(int *a){
int c = (*a)*10; // but you dont change a
return c; // instead you return a new value
}
int main(){
int num = 4;
value(&num); // but here you ignore the new value.
printf("value of number is = %d", num);
return 0;
}
to make reference way work you need
#include <stdio.h>
void value(int *a);
int main(){
int num = 4;
value(&num);
printf("value of number is = %d", num);
return 0;
}
void value(int *a){
*a = (*a)*10; // chnage the value that a points at
// no need to retunr anything
}
or to make the return way work
#include <stdio.h>
// no need to pass by reference
int value(int a);
int main(){
int num = 4;
num = value(num); // use value return by function
printf("value of number is = %d", num);
return 0;
}
int value(int a){
int c = a * 10;
return c;
}