I'm meant to have decent c programming experience, but I've hit a snag with globals.
I'll give a code example soon, but explain first.
If I declare a certain variable name globally, and later feed this var name by reference to a function, which then changes the value, how come other functions fail to see this value change in the globally declared variable name. example:
So here I declare "sz" as a global int. In my main section I allocate the value 12 to it. Then I use function allarr() to change this value. My main section does in fact register these changes in value. My problem is that the addthem() function doesn't. It doesn't see any change in value whatsoever. In my tests, it outputs sz as zero, not 12, not 9.
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
5 int i, sz;
7 void allarr(int *arr, int *sz)
9 printf("from allarr, sz is %i\n",*sz);
15 int addthem(int *arr)
17 int sum=0;
18 printf("from addthem, sz is %i\n",sz);
21 return sum;
24 int main(int argc, char *argv)
27 int *ar, sz=12;
30 /* print stuff out */
32 printf("%i ", ar[i]);
34 printf("addthem: %i\n",addthem(ar));
37 return 0;
Where I confuse myself also (not hard to do, as you can see) is that by passing "sz" to function allarr() by reference, I essentially change the nature of the variale name for the function allarr(), because presumably, as a global, it was aware of "sz" being an int, but now it receives this name as an int*. This local definition of "sz" seems to supplant the global definition, for the allarr() function at least.
Meanwhile, back in main(), no such re-definition has taken place, and it registers the new values of "sz" without problems.
So I'm not sure what's going on. Have I changed a variable's global scope into a local scope? That's a hunch, any comments welcome. Thanks!