二级指针与const

发布时间 2023-06-01 17:24:56作者: hacker_dvd

二维数组分配:

#include <iostream>

int main() {
  int rows = 3;
  int cols = 4;
  // 使用二级指针创建一个动态分配的二维数组
  int **array = new int*[rows];
  for (int i = 0; i < rows; i++) {
    array[i] = new int[cols];
  }
  // 给数组赋值
  int count = 0;
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      array[i][j] = count++;
    }
  }
  // 打印数组
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      cout << array[i][j] << " ";
    }
    cout << endl;
  }
  // 释放内存
  for (int i = 0; i < rows; i++) {
    delete[] array[i];
  }
  delete[] array;

  return 0;
}

采用智能指针:

#include <iostream>
#include <memory>

int main() {
  int rows = 3;
  int cols = 4;

  // 使用 std::unique_ptr 创建一个二维数组
  auto array = std::make_unique<std::unique_ptr<int[]>[]>(rows);
  for (int i = 0; i < rows; i++) {
    array[i] = std::make_unique<int[]>(cols);
  }

  // 给数组赋值
  int count = 0;
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      array[i][j] = count++;
    }
  }

  // 打印数组
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      std::cout << array[i][j] << " ";
    }
    std::cout << std::endl;
  }

  return 0;
}

使用 std::array 创建数组

#include <iostream>
#include <memory>

int main() {
  int rows = 3;
  int cols = 4;

  // 使用 std::unique_ptr 创建一个二维数组
  auto array = std::make_unique<std::unique_ptr<int[]>[]>(rows);
  for (int i = 0; i < rows; i++) {
    array[i] = std::make_unique<int[]>(cols);
  }

  // 给数组赋值
  int count = 0;
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      array[i][j] = count++;
    }
  }

  // 打印数组
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      std::cout << array[i][j] << " ";
    }
    std::cout << std::endl;
  }

  return 0;
}

二级指针与 const

#include <iostream>

int main() {
  int x = 5;
  int y = 10;

  int *p1 = &x;
  int *const *p2 = &p1; // p2 是一个指向常量指针 p1 的指针

  *p2 = &y; // 错误:不能修改常量指针 p1 的值
  **p2 = 20; // 正确:可以修改 p1 指向的值

  const int **p3 = &p1; // p3 是一个指向指向常量整数的指针的指针

  *p3 = &y; // 正确:可以修改 p1 的值
  **p3 = 20; // 错误:不能修改常量整数的值
  char x = 'A';
  char y = 'B';

  char const* p1 = &x;
  char const*const* a = &p1;
  // 这里也可以写为 const char *const* a = &p1;

  std::cout << **a << std::endl; // 输出 'A'

  // *a = &y; // 错误:不能修改常量指针 p1 的值
  // **a = 'C'; // 错误:不能修改常量字符 x 的值

   return 0;
}