diff options
-rw-r--r-- | 01-13.md | 19 |
1 files changed, 10 insertions, 9 deletions
@@ -11,24 +11,24 @@ Notes 01/13/2020 - The pointer `*px` is "pointing" to the memory address where x is located (`&x`) - The pointer must be assigned a data type (in this case `int`) that matches the memory type that it is pointing to - +``` x = 5; *px = 1 printf("%d", x); - +``` - The code above will print `1` because `*px` (the value in the memory address that px is pointing to) was changed to 1, so x was changed to 1 - You can change where the pointer is pointing to: `px++` changes the pointer to point to the next memory address - This is useful when dealing with arrays: - +``` int x[5] = {1, 2, 3, 4, 5} int *px; px = &x[0]; //can also be written px = x printf("%d", *px); px++; printf("%d", *px); - +``` The code above would print `1` and then `px++` would move the pointer to point to `x[1]` and the second number printed would be `2` @@ -112,26 +112,27 @@ The above code would print `STRING!` - A function can also receive an array as an argument in the form of a pointer - For Example: - +``` void my_function(char *c){ ... } - +``` - The function would receive a memory address pointing to a char. It would be beneficial to pass a memory address pointing to a string. - Let's flesh-out the example: - +``` void my_function(char *c){ printf("%s\n", *c); c++; printf("%s\n", *c); } - +``` - Let's say we pass a memory address `&my_string[0]` and my_string is defined as `char my_string[] = "Hello World"` - The code would output: - +``` Hello World ello World +``` |