Home


Lesson 3

Pointers

Hello RAM!

I. Introduction

Task 0

Find new language elements.


#include <iostream>
#include <string>

struct house
{
    std::string city;
    std::string street;
    int number;
};

void buyingOnline(house *addr)
{
    std::cout << (*addr).city   << std::endl
              << (*addr).street << std::endl
              << (*addr).number << std::endl;
}

int main()
{
    house home;
    home.city = "Warsaw";
    home.street = "Koszykowa";
    home.number = 86;

    buyingOnline(&home);
}

II. Pointers to simple values

Task 1

Change question marks into proper c++ statements.


#include <iostream>

using std::cout;
using std::endl;

int main()
{
    int x = 10;

    cout << "address of x: " << ? << endl;
    cout << "show value of x using its address: " << ? << endl;

}
Task 2
  1. Create a new variable called "px". It should refer to a variable "x".
  2. Using "px" increase value of "x" by 3.
  3. Make "px" refering to "y".
  4. Increase value of "px".
  5. Try to increase the value, which "px" refers.
  6. Describe mechanisms of pointners operating.

#include <iostream>

using std::cout;
using std::endl;

int main()
{
    int x = 10;
    int y = 20;
}
Task 3
  1. Create two methods. One should take "int" as an argument, the second "int*".
  2. Each method should increase values of each given argument.
  3. Call methods using one variable in main's body.
  4. Describe the difference between two methods.

III. Dynamic arrays

Zadanie 4

Analyse code written below. Describe all new elements.


#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
using std::cin;

int main()
{
    int size;
    cout << "Type a size for the array: ";
    cin >> size;

    int *arr = new int[size];

    for (int i = 0; i < size; ++i)
    {
        cin >> arr[i];
    }

    delete[] arr;
}
    
Task 5
  1. Display the value of *arr. What it relates to?
  2. Modify the code from task 4 to avoid using "[ ]" braces to access the array.

IV. Pointners and structures

Task 6

Analyse the code written below. One of the statements is invalid. Comment the wrong line.


#include <iostream>
#include <string>
#include <cstdlib>

using std::cout;
using std::endl;
using std::cin;

struct house
{
    std::string city;
    std::string street;
    int number;
};

int main()
{
    house *h = new house();
    
    *h.city = "Warsaw";
    (*h).street = "Koszykowa";
    h->number = 86;

    free(h);
}
        
Task 7

Which definition of a list element is correct? Why?


// A
struct item {
    item next;
};
                    

// B
struct item {
    item* next;
};