Pointer Manipulation in C -
hey ! beginner programmer , need pointers. trying do: have 2 pointer arguments function(caller), arg1 , arg2. want manipulate these pointers inside other function, func, such change reflects in caller func called. right change make in function gets undone in calling function. here source code:
func(node* arg1, node* argv2) { node* point3 = (struct node*) malloc(struct node); arg2 = arg1; arg 1 = point3; } caller(node* argv1, node* argv2) { func(arg1, arg2); }
now know can done using pass reference technique. func becomes func(node** arg, node** arg2)
, dont want double pointers. thinking more on lines of how array when manipulated or changed in function changes functions in program. please me out !
there 2 ways it:
1) swap pointers, need use double pointers(**
)
func(node** arg1, node** arg2) { node* tmp = *arg2; *arg2 = *arg1; *arg1 = tmp; }
2) swap content, think can this:
func(node* arg1, node* arg2) { node* tmp = (struct node*) malloc(sizeof(struct node)); node* clean = tmp; *tmp = *arg2; *arg2 = *arg1; *arg1 = *tmp; free(clean); }
method #1 more efficient since swap pointers instead of whole struct. , mentioned, should use sizeof()
inside malloc.
Comments
Post a Comment