The basics of programming in c++ for beginners

Tasks and Solutions: Pointers C ++

Тему Указатели в C мы рассмотрели в двух статьях:

–  Part 1: C++ Pointers

– Part 2: C++ Pointers

Теперь вам придется много практиковаться, чтобы закрепить знания и до конца разобраться. Решим несколько задач для начала.

1.  The task of the elementary, but it requires a good understanding of what pointers. Dan pointer: double **p = 0; Perform the following tasks (solutions can execute within the function main):
* create a design, shown in Figure;
* print number, specified in the box, the screen;
* then delete all dynamic objects.

with the solution of the problem, C ++ pointers

Yet again – We are looking for the shortest solution. Author:  

2. Объявите указатель на массив типа double и предложите пользователю выбрать его размер. Далее напишите четыре functions: первая должна выделить память для массива, second– заполнить ячейки данными, третья – показать данные на экран, четвертая – освободить занимаемую память.  The program should prompt the user to continue working (создавать новые динамические массивы ) or withdraw from the program.

3. Объявите указатель на массив типа int и выделите память память для 12-ти элементов. It is necessary to write a function, которая поменяет значения четных и нечетных ячеек массива. Например есть массив из 4-х элементов:

задачи и решения указатели c++

задачи и решения указатели c++

4.  Declare and populate a two-dimensional array of dynamic random numbers from 10 to 50. Показать его на экран. Для заполнения и показа на экран написать отдельные функции. (подсказка: функции должны принимать три параметра – указатель на динамический массив, количество строк, количество столбцов).  The number of rows and columns the user selects.

40 thoughts on “Tasks and Solutions: Pointers C ++

  1. I do not understand the decision of the first task
    Either I have read and watched bad vidos, or I just forgot something, but as I understand, the pointer – a pointer to a pointer, верно?
    I.e, one line of code, we create two pointers, one of which points to another pointer, which in turn points to the 2.
    Listen as nonsense
    I have a lot of questions,
    As the pointer points to a deuce? Or there is also a variable is created?
    why first, there is need to put * and then there?
    *(*(p = new double*) = new double) = 2;
    And what's going on in this line, I did not understand
    Who understands this help please, I do not understand

    1. P pointer is assigned an address dynamically allocated memory that stores a pointer to a double, Next we razadresuem p and obtain a pointer to type double, and dynamically allocates memory to him, razadresatsiey obtain the value of the memory cell (с double) and assign it a value 2.Can be written differently:
      p = new double*;
      *p=new double;
      **p=2;

      1. Thank you, in principle I like this and thought, only in my head, it seemed much more difficult

  2. By 4 you can tell the task why this error occurs
    “caused the breakpoint to fire”
    not every time .

  3. Read the lessons and watched the video up to this point, I'm trying to understand with a squeak:
    по 2 task, //double* pArrForFill = 0;// how we made a pointer to an array in this way? like the address of the first cell?
    And, why is that:
    //double* giveMemoryToArr(double* ptrArr, int sizeOfArr)
    {
    ptrArr = new double[sizeOfArr];//
    not like this?
    //double* giveMemoryToArr(double* ptrArr, int sizeOfArr)
    {
    double* ptrArr = new double[sizeOfArr];//

    1. double* pArrForFill = 0
      we create a pointer but it is just empty
      //double* giveMemoryToArr(double* ptrArr, int sizeOfArr)
      {
      double* ptrArr = new double[sizeOfArr];//
      this way we re-create the pointer and why do we need to do this when we already have it and we pass it to the function?

  4. 3 a task:
    #include

    using namespace std;
    void fillArr(int* parr);

    int main()
    {
    setlocale(LC_ALL, “rus”);

    int arr[12]{};
    cout << "Массив до функции:\n";
    cout << "___________________________\n";
    for (int i = 0; i < 12; i )
    {
    arr[i] = i + 1;
    cout << arr[i] <<"|";
    }
    fillArr(arr);
    cout << "\n___________________________\n";
    cout << "\nМассив после функции: \n";
    cout << "___________________________\n";
    for (int i = 0; i < 12; i )
    {
    cout << arr[i] << "|";
    }
    cout << "\n___________________________\n";
    return 0;
    }
    void fillArr(int* parr)
    {

    for (int i = 1; i < 12; i = 2)
    {
    int j = parr[i – 1];
    parr[i – 1] = parr[i];
    parr[i] = j;
    }
    }

  5. Problem No. 3
    #include
    using namespace std;

    void FillArray(int* arr, int size)
    {
    for (int i = 0; i < size; i )
    {
    arr[i] = rand() % 100;
    }
    }

    void OutputArray(int* arr, int size)
    {
    for (int i = 0; i < size; i )
    {

    cout << i+1 << ": " << arr[i] << "\t";
    }
    cout << endl;
    }

    int main()
    {
    int size = 12;
    int* arr = new int[size];
    FillArray(arr, size);
    OutputArray(arr, size);
    for (int i = 0; i < size; i )
    {
    if ((i+1) % 2 == 0)
    {
    arr[i] = arr[i] + arr[i – 1];
    arr[i – 1] = arr[i] – arr[i – 1];
    arr[i] = arr [i] – arr[i – 1];
    }
    }
    OutputArray(arr, size);
    return 0;
    }

  6. task №3
    I see a solution like this, simpler as it seems to me
    void fuu(int* pmas)
    {
    for (int i = 0; i < 12; i )
    {
    pmas[i] = i + 1;
    cout << " | " << pmas[i];
    }
    cout << "\n\n============================================\n\n";
    for (int ix = 0; ix 0)
    pmas[ix] = pmas[ix] + 1;
    else
    pmas[ix] = pmas[ix] – 1;
    }

    }
    void main()
    {
    setlocale(LC_ALL, “rus”);
    int * mas = new int[12];
    fuu(but);
    for (int i = 0; i < 12; i )
    {
    cout << " | " << but[i];
    }
    }

  7. Wouldn't it be easier to decide 3 tasks so?:
    //librayes
    #include
    //std
    using namespace std;

    void swapOddAndShow(int* &p, int size) {
    for (int i = 0; i < size; i ) {
    if (p[i] % 2 == 0) {
    p[i – 1] = p[i];
    p[i] = p[i – 1] – 1;
    }
    }
    for (int i = 0; i < size; i ) { //void swapOddAndShow
    cout << p[i] << endl;
    }

    }

    int main()
    {
    const int size = 12;
    void swapOddAndShow[size];
    for (int i = 0; i < size; i ) { //void swapOddAndShow
    pArr[i] = i + 1;
    cout << pArr[i] << endl;
    }

    cout << "=======================" << endl;

    void swapOddAndShow(pArr, size);

    delete[] pArr;
    }
    void swapOddAndShow, void swapOddAndShow.

Leave a Reply

Your email address will not be published. Required fields are marked *