I\'m trying understand how to pass a parameter by reference in C language. So I wrote this code to test the behavior of parameters passing:
#include
You want to modify the value of n
in main
, not what n
points to, so you need to pass a pointer to it. Since the type of n
in main
is int *
, the parameter to alocar
needs to be of type int **
:
void alocar(int **n)
{
*n = malloc(sizeof **n); // note no cast, operand of sizeof
if (!*n)
exit(-1);
**n = 12;
printf("%d\n", **n);
}
int main(void)
{
int *n;
alocar(&n);
printf("%d\n", *n); // we've already tested against n being NULL in alocar
free(n); // always clean up after yourself
return 0;
}