R
ramif
Does call by reference principle apply to pointers??
Is there a way to pass pointers (by reference) to functions?
Here is my code:
#include <stdio.h>
#include <stdlib.h>
// f() is supposed to change num's value to 88...
void f(int *num)
{
int *num2 = malloc( sizeof(int) );
*num2 = 88;
//*num = 88; //data OUTSIDE f() is changed
num = num2; //data OUTSIDE function f() will not change...
free(num2);
}
main()
{
int *x = malloc( sizeof(int));
*x = 5;
printf("x = %d\nExecuting f()...\n", *x);
f(x); //calling f() to change the value of x
printf("x = %d\n", *x); //ERROR: X DID NOT CHANGE
free(x);
}
Is there a way to pass pointers (by reference) to functions?
Here is my code:
#include <stdio.h>
#include <stdlib.h>
// f() is supposed to change num's value to 88...
void f(int *num)
{
int *num2 = malloc( sizeof(int) );
*num2 = 88;
//*num = 88; //data OUTSIDE f() is changed
num = num2; //data OUTSIDE function f() will not change...
free(num2);
}
main()
{
int *x = malloc( sizeof(int));
*x = 5;
printf("x = %d\nExecuting f()...\n", *x);
f(x); //calling f() to change the value of x
printf("x = %d\n", *x); //ERROR: X DID NOT CHANGE
free(x);
}