pointers - C, pass to function by reference. Pass forward -
i understood meaning of passing reference , value in c, in program "pass forward" reference function, neatness purposes, instance:
void f2(int *x2) { *x2 = 7; } void f1(int *x1) { *x1 = 4; f2(x1); } int main() { int x = 1; f1(&x); printf("%d\n",x); return 1; }
does main function print out 4 or 7? moreover, if sure pass reference f2
inside f1
, idea do:
void f1(int *x1) { *x1 = 4; int x2; &x2 = x1; f2(&x2); }
but don't find elegant , fast (in program use instead of int
pretty big structs
, avoid creating copy inside every function). soultion work anyway? there more elegant , faster way?
thanks in advance
edit:
i tested , first snippet compile , works expected (main prints out 7). first method right way. second code snippet wrong , not compile
in c, there's neither reference nor there pass reference concept. arguments always passed value.
you can emulate pass reference semantics using pointers. of course, can pass on pointer. pointer passed value (see first paragraph), each function has own copy. value (the address points to) doesn't change, each function can access data pointer points to.
your second code snippet doesn't make sense. it's impossible change address of variable. and, should've understood rest of answer, whatever tried there unnecessary anyways.
Comments
Post a Comment