IFD:EAI SoS21/course material/Session 3: File Structuring, Pointers and Addresses

From Medien Wiki

Homework/Recap from Session 2:

Here are the solutions of last week's task. Please try a little to solve on your own, before you peek in here! :)

To get the distance between two points on a 2D plane we can use the Pythagorean theorem as depicted in the picture below. We give coordinates to the points and use the coordinates to calculate the distance according to the formula c = sqrt( (x2-x1)^2 + (y2-y1)^2 ), where c is the distance between the two points.

Distance calc.png

To get the x- and y-coordinates in our code, we can use the private variables for point p1 (_x and _y) and the member functions getX() and getY() for point p2. So the most crucial lines of code are:

float Point2D::calculateDistanceToOtherPoint(Point2D p2){
    float distance = sqrt( (p2.getX() -_x)*( p2.getX() -_x)+( p2.getY()-_y)*( p2.getY() -_y) ); 
    return distance;
}

Note that, for the sqrt() function to be known to the compiler, you need to include the math library with

#include <math.h>

Distance Function Complete Code

File Structuring, Preprocessing & Compilation

Filestructure preprocessing compilation1.png

Pointers and Addresses

Until now, we were only using variables in a very local space in the main memory, called the stack. The stack is a very compact structure where most of the variables and program code usually reside. It's called "stack" because the variables really stack up there, on after the other, depending of the order you instantiate them. The syntax for creating a Point2D as a stack variable is as follows:

Point2D p1 = Point2D(1,2);

If we use pointers however we can use memory space everywhere in the main memory. This space is used by other programs as well and rather loosely organized. This is why it is called "heap". When we create a pointer to our Point2D, the syntax is like this:

Point2D* p2 = new Point2D(1,2);
...
delete p2;

We need to use the asterisk to denote, that we want to create a pointer and we need to use the "new" keyword to reserve the memory for our Point2D. After the "new" keyword we can initialize our Point2D directly as shown before. Note that p2 resides in the memory, when we do not delete it explicitly. Usually until you restart your computer!

Code Example for Pointers and Addresses Pointers addresses1.png