Reputation:
Using 2 facts about C,
In C programming, an integer pointer will point to an integer value whose address is provided to the pointer.
And in pass by reference, we are actually passing the original variable's address to a function.
so, is the following acceptable :
#include<stdio.h>
void square(int *p)
{
*p = (*p)*(*p);
}
int main()
{
int var = 10;
square(&var); // Address of the variable
printf("\nSquared value : %d",var);
return 0;
}
Though this is doing the same work (if not wrong) as the following :
#include<stdio.h>
void square(int *p)
{
*p = (*p)*(*p);
}
int main()
{
int var = 10;
int *ptr;
ptr = &var;
square(ptr); // Pointer as the argument
printf("\nSquared value : %d",var);
return 0;
}
Upvotes: 2
Views: 84
Reputation: 224387
In both cases you're passing the address of var
to the function, so both are fine.
Upvotes: 3