I learn that in order to access or modify the value of a variable by calling a function, we need to pass pointers as arguments such as below :
#include <stdio.h>
//create a function
void Increment(int* x) {
*x = *x+1;
printf("Address of variable x in increment = %p\n",x);
}
int main() {
int a;
a = 10;
Increment(&a);
printf("Address of variable 'a' in main = %p\n",&a);
printf("Value of a in main function = %d\n",a);
}
But I did another test, and I found out that by calling the function and returning the value, I can also achieve the same result.
#include <stdio.h>
//create a function
int Increment(int x) { // do not use VOID
x = x+1;
printf("Address of variable x in increment = %p\n",x);
return x;
}
int main() {
int a;
a = 10;
int hasil;
hasil = Increment(a);
printf("Address of variable 'a' in main = %p\n",&a);
printf("Value of a in main function = %d\n",hasil);
}
My questions :
1) Do I have to pass pointers as argument if I can just use return value to achieve the same result?
2) I observe when I print the address of the memory of variable 'x' from the function that returns value, the memory address is very short 0xb , any idea why? normally the address is very long.