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. Overall good. Didn't read into it, looked diagonally. The pictures are beautiful.

    I would not write functions like giveMemoryToArr (although, for taste and color…).
    If we leave them, then IMHO double* freeMemory(double* ptrArr) should return void. Why does it always return zero??

    Some other example (more voluminous)… Checkers (man against man) whether…

    Generally, well done. Write more :)

  2. Thank you very much to the admin, за то, which gives not only tasks, and solutions with detailed comments to the code. I read C++ tutorials on several sites. On your – I like it the most. Convenient home page content, problems with solutions on a separate page. Why are tasks grouped by topic?, and not everything in a crowd and mixed up.
    Don't stop! Write more! :)

  3. So maybe the task can be done 3 and solve without buffers:
    void mixmass(int no, int *arr)
    {
    for (int i = 1; i < sz; i )
    {
    if (arr[i] % 2 == 0)
    arr[i] = i-1;
    }
    }
    ————————————————————–
    for (int i = 0; i < sz; i )
    {
    mass [i] = i+1;
    std::cout << mass [i] << std::ends;
    };

    mixmass(sz, mass);

    But I don't get it..

  4. The first problem contains a bunch of incomprehensible structures, there were no explanations for them in previous lessons, so why solve the problem in a way, which is not clear to students?

    1. In the 1st problem there are no “designs” – you just need to understand it well, what:
      a). the pointer contains адрес Togo, what is he pointing to,
      b). and the operation denaming a pointer (prefix operation *) means: “take value Togo, what does the pointer point to?”.

      1. This I know, it was in the lesson. But 4 string, where void is in parentheses, I can't understand at all, there was never anything in parentheses in the lessons;
        String 6, where nothing is clear at all, there were no such structures in the lessons. The tasks should be like this, that after reading all the previous articles they could be easily understood. But the first task is not like that at all.

  5. 3 a task

    #include
    using namespace std;

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

    int* array = new int[12];
    for (int i = 0; i < 12; i )
    {
    array[i] = i + 1;
    cout << array[i] << " ";
    }

    cout << endl;

    int b = 0;
    int j = 1;
    int save = 0;
    for (int i = 0; i < 6; i )
    {
    save = array[b];
    array[b] = array[j];
    array[j] = save;

    b = b + 2;
    j = j + 2;
    }

    for (int i = 0; i < 12; i )
    {
    cout << array[i] << " ";
    }

  6. Guys, if it's not difficult, help me with the problem: Given are matrices A and B of size k×m and m×l, respectively. Find the product AB. Implement matrix multiplication as a function.

    1. The matrix multiplication problem itself – “if it's not difficult” (and even elementary – 2 nested loop).
      But:
      1. There are different options for representing 2-dimensional matrices (as 2-dimensional arrays, like arrays of pointers, like STL containers – vector of vectors, etc.. … to 10 different ways or more). Depending on the chosen method, calculations will be written completely differently..
      2. Much larger in volume, than multiplication itself, will take you a). input of initial matrices + b). output result + in). test task main() which will clearly demonstrate the process and result.

      So the task is very simple, but write everything for it framing – not at all easy, there is a lot of mechanical work.

  7. People, what if I want to write a function for allocating memory for a two-dimensional array, what does it look like.

    int *givemmry (int **boob, int size1,int size2)
    {
    **boob = new int* [size1];
    for (int i = 0; i < size1; i )
    {
    boob[i] = new int[size2];
    }
    return **boob;
    }

    so it gives an error


    1. int** givemmry( int size1, int size2 ) {
      int **boob = new int* [ size1 ];
      for( int i = 0; i < size1; i++ )
      boob[ i ] = new int[ size2 ];
      return boob;
      }

      Or easier:

      int** givemmry( int size1, int size2 ) {
      return (int**)new int* [ size1 * size2 ];
      }

      1. In the 2nd solution, an error crept in by copying, there must be, naturally:

        int** givemmry( int size1, int size2 ) {
        return (int**)new int [ size1 * size2 ];
        }

  8. Thank you! as I understand it, it is not necessary to specify the type and index of the array (boob) in function argument, we just return the value?

    1. Here the parameter turns out to be simply superfluous – you will still overwrite its value after new, and his type (and array elements) you still can't change it.

Leave a Reply

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