C Tutorial Session 3 Pointers continued External Variables
C Tutorial Session #3 • Pointers continued • External Variables and Scope • Debugging with ddd
Review: pointers w Pointer variable presents a memory address. w The difference between pointer variables and regular variables. int A memory Stores the value of A int *B Stores a memory address of an integer
Example 1 foo int foo = 100; int *bar; 0 x 1000 bar 0 x 1020 Question: what is 1. foo; 3. bar; 5. &bar; 100 2. &foo; 4. *bar; uninitialized
Example 2 int foo = 100; int *bar; bar = &foo; foo 0 x 1000 bar 0 x 1020 Question: what is 1. foo; 3. bar; 5. &bar; 100 2. &foo; 4. *bar; 0 x 1000
Example 3 int foo = 100; int *bar; bar = &foo; *bar = 200; Question: what is 1. foo; 3. bar; 5. &bar; 2. &foo; 4. *bar; foo 0 x 1000 100 200 bar 0 x 1020 0 x 1000
Pass by value int increase(int a){ a++; return a; } int main(){ int foo = 0; int bar = increase(foo); }
Using pointers as arguments int increase (int *a){ (*a)++; } int main () { int foo = 0; int bar = increase (&foo); }
Variables and Scope w Variables declared within a function n n private, local, automatic can only be accessed within that function w External (Global) variables n n Declared ONCE at the top of ONE source file Other source files may access/declare that same variable using the extern declaration
Scope (cont. ) file 1: file 2: extern int sp; extern double val[]; int sp = 0; double val[MAXVAL]; void push (double f) {…} double pop (void) {…}
Definitions and Declarations among shared files calc. h #define NUMBER '0' void push (double); double pop (void); int getop (char []); int getch (void); void ungetch (int); main. c getop. c #include <stdio. h> #include <stdlib. h> #include "calc. h“ #define MAXOP 100 main () { … } #include getop () stack. c <stdio. h> <ctype. h> "calc. h" { … } getch. h #include <stdio. h> #define BUFSIZE 100 char buf[BUFSIZE]; int bufp = 0; int getch (void) { … } void ungetch (int) { … } #include <stdio. h> #include "calc. h" #define MAXVAL 100 int sp = 0; double val[MAXVAL]; void push (double) { … } double pop (void) { … }
Static Global Variables w Declaring a variable (or functions) as static limits the scope to the rest of the source file being compiled. static char buf [BUFSIZE] /* buffer for ungetch */ static int bufp = 0; /* next free position in buf */ int getch (void) { … } void ungetch (int c) { … } w The static declaration means that both functions within this source file can access these variables, but others can’t.
Static Local Variables In a compiled program there are 2 main areas for variable storage: w Stack – used for called functions and local variables. Goes away when a function returns. w Heap – used for global allocation and external variables. Declaring a local variable as static, allocates it on the heap. This is useful for large arrays and allocations.
Debugging with ddd
- Slides: 13