

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Memory
incomplete
2: What Is an Address?
incomplete
3: Virtual Memory
incomplete
4: Pointers
incomplete
5: Why Pointers?
incomplete
6: Pointer Basics
incomplete
7: Pointers to Structs
incomplete
8: C Arrays
incomplete
9: Arrays As Pointers in C
incomplete
10: Multibyte Arrays
incomplete
11: Array Casting
incomplete
12: Pointer Size
incomplete
13: Arrays Decay to Pointers
incomplete
14: C Strings
incomplete
15: C String Library
incomplete
16: Forward Declaration
incomplete
17: Mutual Structs
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
To illustrate the usefulness of pointers, let's pretend we want to pass a collection of data into a function. Within that function, we want to modify the data. In Python, we could use a class to store the data, and pass an instance of that class into the function:
class Coordinate:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def update_coordinate_x(coord, new_x):
coord.x = new_x
c = Coordinate(1, 2, 3)
print(c.x) # 1
update_coordinate_x(c, 4)
print(c.x) # 4
Now let's do the same thing, but using a struct in C.
Complete the coordinate_update_x and coordinate_update_and_return_x functions.
Remember, you can access the field of a struct with a . operator, like so:
car.tires = 4;
After passing the assignment, open up main.c and take a look at the test cases. You'll notice that coordinate_update_x doesn't update anything, but coordinate_update_and_return_x does because it returns a new copy of the struct.
main function.coordinate_update_and_return_x was not the same as the address of the struct that was returned. Again, because we created a copy.