I try it :
#include
#include
void foo(int* x)
{
x = (int *)malloc(sizeof(int));
*x = 5;
}
int main()
{
int a;
You are changing the pointer value in foo by the malloc call - just do this:
void foo(int* x)
{
*x = 5;
}
In your code - this function:
void foo(int* x)
{
x = (int *)malloc(sizeof(int));
*x = 5;
}
Works as follows:
+----+
| a |
+----+
/
x points here
Then you make x point somewhere else:
+----+ +----+
| 5 | /* created by malloc*/ | a |
+----+ +----+
/ On Heap / On Stack
x now points here a is now in memory somewhere not getting modified.
And you make it 5. Also note - x is a local copy of the &a address of a - in C there is no pass by reference but only pass by value - since the variables value is copied into the function.