Pointers
Content |
We start with some simple examples on pointers. Recall:
-
With &i we get the address of a variable i. If i has type int then &i is of type int *.
-
Assume j is a pointer to int (i.e. of type int *) then the content of j is interpreted as the address of an integer. With *j we can denote the value stored at address j (the value j points to).
-
With sizeof() we get the size of a variable of a type in bytes:
-
sizeof(i), sizeof(j) gives the size of variables i and j respectively.
-
sizeof(int), sizeof(int *) gives the size of types int and int * respectively.
-
Example: Modify a variable indirectly
int main() { int i = 3; int *j = &i; *j = 5; return i; }
Exercise:
-
Compile and run the program. Check the exit code.
-
Modify the program such that it prints the value of i before and after it gets changed indirectly. Also print:
-
the address of i,
-
the size of i and the size of int,
-
the size of j and the size of int *.
In your code:
-
Use a forward declaration for function printf.
-
Use the %d placeholder to print a integer value.
-
Use the %p placeholder to print an address. Note that %p expects a pointer to void so you need a cast (even if it will work on most computers without cast).
-
Use %zu to print size of type or variable.
-
Example: Call by reference
In the following example function foo is supposed to change it argument to value 5. An experienced Fortran programmer (but new to C) tries the following:
int printf(const char *, ...); void foo(int i) { i = 5; } int main() { int i = 3; printf("i = %d\n", i); foo(i); printf("i = %d\n", i); }
-
Why is this not working?
-
Make it work by applying the pattern: Call by reference is realized by passing a pointer by value.