a globals changes value via function argument
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:
Code:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 int i, sz;
6
7 void allarr(int *arr, int *sz)
8 {
9 printf("from allarr, sz is %i\n",*sz);
10 *sz=9;
11 for(i=0;i<*sz;i++)
12 arr[i]=i;
13 }
14
15 int addthem(int *arr)
16 {
17 int sum=0;
18 printf("from addthem, sz is %i\n",sz);
19 for(i=0;i<sz;i++)
20 sum+=arr[i];
21 return sum;
22 }
23
24 int main(int argc, char *argv[])
25 {
26
27 int *ar, sz=12;
28 ar=malloc(sz*(sizeof(int)));
29 allarr(ar,&sz);
30 /* print stuff out */
31 for(i=0;i<sz;i++)
32 printf("%i ", ar[i]);
33 printf("\n");
34 printf("addthem: %i\n",addthem(ar));
35
36 free(ar);
37 return 0;
38 }
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.
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!