Sta_c: When we define a variable int gvar; int square(int x) { int d; d = x * x return d; } int main() { int a; int b; int c; int x; a = 2; b = 5; c = a + b; … Allocate memory in global storageAllocate memory in local storage 5 23 6 10 2 3 27 0 4 100 104 108 112 116 120 124 128 132 136 gvar Calculate c = a + b 1.? Take the value from the loca_on represen_ng a 2.? Take the value from the loca_on represen_ng b 3.? Add the two values 4.? Store the result at the loca_on represen_ng c 5 23 6 10 2 0 4 100 104 108 112 116 120 124 128 132 136 gvar Q: How do we find “the loca_on represen_ng a”? Find the Variables int gvar; int square(int x) { int d; d = x * x return d; } int main() { int a; int b; int c; int x; a = 2; b = 5; c = a + b; … 0 4 100 104 108 112 116 120 124 128 132 136 A: The compiler knows exactly how many and where to find each variable if they are defined sta£cally. global area main() gvar a b c x x d square() Passing the Variable Loca_ons Around ?? How do you tell something else where can it find a par_cular variable? ?? We use the ampersand symbol(&) to “get the address” of a variable. ?? Note: It is similar to the C++’s concept of reference, but not exactly the same. ?? You can then use the address like any other value, e.g. •? Get the next address next to b •? Pass the address to a func_on so that it knows “how to find b”. 5 23 6 10 2 3 27 0 4 100 104 108 112 116 120 124 128 132 136 gvar a b c x x d &b findx(&b); next_address = &b + 1 Pointers ?? Loosely speaking, “the address of a variable is called a pointer”. ?? “A pointer to something” can be thought as “the address of something.”. •? E.g. “a pointer to an integer x” is essen_ally “the address of an integer x.” ?? The C/C++ type of a pointer to a type T is denoted as T* •? The type “pointer to an integer”: int* •? The type “pointer to a struct of image”: struct image* int *iptr; float *fp; struct image *img;
Download C Pointers.
0 comments:
Post a Comment