When to pass pointers in functions?
Posted
by yCalleecharan
on Stack Overflow
See other posts from Stack Overflow
or by yCalleecharan
Published on 2010-04-05T18:53:02Z
Indexed on
2010/04/05
19:13 UTC
Read the original article
Hit count: 158
scenario 1
Say my function declaration looks like this:
void f(long double k[], long double y[], long double A, long double B) {
k[0] = A * B;
k[1] = A * y[1];
return;
}
where k and y are arrays, and A and B are numerical values that don't change. My
calling function is
f(k1, ya, A, B);
Now, the function f is only modifying the array "k" or actually elements in the
array k1 in the calling function. We see that A and B are numerical values that
don't change values when f is called.
scenario 2
If I use pointers on A and B, I have, the function declaration as
void f(long double k[], long double y[], long double *A, long double *B) {
k[0] = *A * *B;
k[1] = *A * y[1];
return;
}
and the calling function is modified as
f(k1, ya, &A, &B);
I have two questions:
- Both scenarios 1 and 2 will work. In my opinion, scenario 1 is good when
values A and B are not being modified by the function f while scenario 2
(passing A and B as pointers) is applicable when the function f is actually
changing values of A and B due to some other operation like *A = *B + 2 in the function declaration. Am I
thinking right?
- Both scenarios are can used equally only when A and B are not being changed in f. Am I right?
Thanks a lot...
© Stack Overflow or respective owner