C/C++

Как разработать динамические переменные с помощью оператора new и при этом удалены оператором delete C++? Можно пример?

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
//-----------------------------
// Под отельный объект
//-----------------------------
auto x = new int;
*x = 12;
cout << setw(4U) << *x << '\n';
if (x != nullptr) {
delete x;
x = nullptr;
}
puts("");
//-----------------------------
// Под одномерный массив
//-----------------------------
auto n = 12U;
auto vector = new(nothrow) int[n];
int m = 0;
for (auto i = 0U; i < n; ++i) {
vector[i] = ++m;
}
for (auto i = 0U; i < n; ++i) {
cout << setw(4U) << vector[i];
}
puts("\n");
if (vector != nullptr) {
delete[] vector;
vector = nullptr;
}
//-----------------------------
// Под двумерный массив
//-----------------------------
auto rows = 8U, columns = 12U;
auto matrix = new(nothrow) int*[rows];
if (matrix != nullptr) {
for (auto i = 0U; i < rows; ++i) {
matrix[i] = new(nothrow) int[columns];
if (matrix[i] == nullptr) {
for (auto j = 0U; j < i; ++j) {
if (matrix[j] != nullptr) {
delete[] matrix[j];
}
}
delete[] matrix;
matrix = nullptr;
break;
}
}
}
if (matrix != nullptr) {
int m = 0;
for (auto i = 0U; i < rows; ++i) {
for (auto j = 0U; j < columns; ++j) {
matrix[i][j] = ++m;
}
}
for (auto i = 0U; i < rows; ++i) {
for (auto j = 0U; j < columns; ++j) {
cout << setw(4U) << matrix[i][j];
}
puts("");
}
}
if (matrix != nullptr) {
for (auto i = 0U; i < rows; ++i) {
if (matrix[i] != nullptr) {
delete[] matrix[i];
}
}
delete[] matrix;
matrix = nullptr;
}
//-----------------------------
system("pause > nul");
}
Баяман Жораев
Баяман Жораев
55 383
Лучший ответ
Для не массива:
char *tmp = new char;
delete tmp;

Для массива:
char *pMem = new char[10];
delete[] pMem;
Baizhan Yershatuly с примитивными типами неважно, массив или не массив.