Теперь вам придется много практиковаться, чтобы закрепить знания и до конца разобраться. Решим несколько задач для начала.
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.
Yet again – We are looking for the shortest solution. Author: Olej
View code
Задача 1: Указатели в С++
C++
1
2
3
4
5
6
7
8
9
10
#include <iostream>
usingnamespacestd;
intmain(void){
double**p=0;
*(*(p=newdouble*)=newdouble)=2;
cout<<**p<<endl;
delete*p;
deletep;
}
2. Объявите указатель на массив типа double и предложите пользователю выбрать его размер. Далее напишите четыре functions: первая должна выделить память для массива, second– заполнить ячейки данными, третья – показать данные на экран, четвертая – освободить занимаемую память. The program should prompt the user to continue working (создавать новые динамические массивы ) or withdraw from the program.
Остановимся на функции, которая выделяет память под массив, размер которого задает пользователь. This functiongiveMemoryToArr(). Определение находится в строках 34 – 38. As seen – as a result, it returns a pointer double. Look – if the function has typevoid, как бы она работала? В нее передался бы указатель и заданный размер. Далее для этого указателя выделяется участок памяти – string 36. And all– при выходе их функции копия указателя уничтожается и адрес этого участка памяти нигде не сохранен. Поэтому функция должна вернуть адрес (pointer) as a result of. That is the memory address of the selected area we will have to be written in the pointer, который объявлен в main() in string 13.
Result:
3. Объявите указатель на массив типа int и выделите память память для 12-ти элементов. It is necessary to write a function, которая поменяет значения четных и нечетных ячеек массива. Например есть массив из 4-х элементов:
Определение функции, которая меняет данные местами, находится в строках 40 – 52. It declared a temporary variablebufferVar. Она будет выполнять роль буфера для значений, которые необходимо будет записать в другую ячейку. Loop for will go through all the cells of the array. If the index– even number(если остаток от деления на 2 is 0), then write down the value of this cell to a variablebufferVar. В саму четную ячейку записывается значение следующей (нечетной): ptrArr[i]=ptrArr[i+1]; And then we have to copy the value of the oddbufferVar: ptrArr[i+1]=bufferVar; Then the cycle and block if перейдут к проверке следующей ячейки.
Результат работы:
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.
View code
Задача 4: Указатели в С++, Двумерный динамический массив
Первое на что надо обратить внимание – это объявление динамического двумерного массива, allocating memory for it and its liberation. When we looked at the topic Двумерные массивы в С мы затрагивали тот вопрос, что двумерный массив – is an array of arrays. Например если объявлен двумерный массив int ArrForChange[3][3], it means that it contains three arrays of three elements each. Объявляется двумерный динамический массив с применением операции ** (двойная звездочка). Это указатель на указатель. Он содержит в себе адрес массива указателей, каждый элемент которого хранит адрес какой-то строки двумерного массива. Визуально это можно показать так:
Сначала надо выделить память под массив, который будет содержать адреса строк двумерного массива:
выделение памяти для двумерного динамического массива
C++
22
int**ArrayForChange=newint*[stringAmount];
You see, что память выделяется не для данных типа int, а именно для указателей на данные типа int.
Далее выделяется память для каждого указателя. В этой памяти уже будут находиться данные типа int:
выделение памяти для двумерного динамического массива
C++
23
24
25
26
for(inti=0;i<stringAmount;i++)
{
ArrayForChange[i]=newint[columnAmount];
}
freeing memory, занимаемую двумерным массивом, надо быть внимательным. Освободить её надо обратным способом: сначала память в которой содержатся данные:
освобождение памяти двумерного динамического массива
C++
32
33
34
35
for(inti=0;i<stringAmount;i++)
{
delete[]ArrayForChange[i];
}
Потом память массива указателей:
освобождение памяти двумерного динамического массива
C++
36
delete[]ArrayForChange;
Если пропустить первый шаг – произойдет утечка памяти. Так как ячейки занимаемые данными, будут отмечены как зарезервированная память и не смогут использоваться в программе повторно.
Передавая двумерный массив в функцию, нам необходимо передать указатель на указатель.
Когда функция получает этот указатель на указатель, она далее может с ним работать, как с обычным двумерным массивом. Например используя вложенные циклы, отображать данные на экран, как показано в строках 44 – 52. Or enter data in cell array– strings 58 – 64.
The result of the program work:
4.7
41
40 thoughts on “Tasks and Solutions: Pointers C ++”
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…
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! :)
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; };
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?
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?”.
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.
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] << " "; }
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.
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.
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; }
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 ]; }
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 ]; }
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?
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.
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 :)
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! :)
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..
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?
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?”.
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.
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] << " ";
}
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.
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.
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
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 ];
}
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 ];
}
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?
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.