c - local variable referenced by a global pointer -


i have question here. have following code

#include <stdio.h> int *ptr;  int myfunc(void); main() {    int tst = 3;    ptr = &tst;    printf("tst = %d\n", tst);    myfunc();    printf("tst = %d\n", tst); }  int myfunc(void) {     *ptr = 4; } 

the local variables stored in stack. made global pointer *ptr , made point local variable in main. now, when call myfunc, local variables of main gets pushed onto stack. in myfunc, change value of pointer , after returning main, check value of local variable has changed. want ask in myfunc, pushed variable tst poped again value changed? beginner please don't mind.

when functions call made, not variables pushed onto stack. arguments of functions pushed onto stack, i.e: ones in parentheses, this: myfunc(arg);. in case, arg pushed onto stack use in myfunc. key remember in c values in variables pushed, not variable itself.

you might after this

#include <stdio.h> int *ptr;  int myfunc(int value); int myfunc2(int *pvalue);  main() {    int tst = 3;    ptr = &tst;    printf("tst = %d\n", tst);    myfunc(*ptr);    printf("tst = %d\n", tst);    myfunc2(ptr);    printf("tst = %d\n", tst); }  void myfunc(int value) {     //here can whatever want value in global ptr     //but when return main not have changed.      value = value + 10;       //has no effect on tst }  void myfunc2(int *pvalue) {     //here argument pointer value. if de-reference pointer value     //with '*' start accessing contents @ address      *pvalue = *pvalue + 10;    //does effect global *ptr } 

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -