C++ Primer Plus 学习笔记 第四章 指针、数组和指针算数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/soulwyb/article/details/89449909
  double wages[3] = {10000.0, 20000.0, 30000.0};
  short stacks[3] = {3, 2, 1};

  double* pw = wages;
  short* ps = &stacks[0];

pw指向wages的第一个元素的内存地址  

&wages指的是整个内存的地址。 所以 sizeof 返回的是整个数组的大小

short *pas[3]指的是指针数组  数组里面全是指针 

    按照符号的优先级规则  pas会先跟[]结合 所以就是pas[3] 这是一个数组 它是short*类型 这样写会更容易看  short* pas[3]

short (*pas)[3] 指的是数组指针  指向一个数组的指针

为了 便于区分  这样子能一目了然  short* pas = new short[3];

    解引用: *pt = pt[0]    一个是指针表示法 一个是数组表示法

绝不要对未被初始化为适当地址的指针接触引用 。会炸

如果需要限制strcpy()中字符串的长度 请使用 strncpy() 。

指针, 数组, 结构 指针数组 数组指针和指针的指针,auto类型的综合例子:

#include <iostream>

struct antarctica_years_end
{
  int year;
};

int main()
{
  antarctica_years_end s01, s02, s03;
  s01.year = 1998;
  antarctica_years_end* pa = &s02;
  pa->year = 1999;
  antarctica_years_end trio[3];
  trio[0].year = 2003;
  std::cout << trio -> year << std::endl;
  const antarctica_years_end* arp[3] = {&s01, &s02, &s03};
  std::cout << arp[1]->year << std::endl;
  const antarctica_years_end** ppa = arp;
  auto ppb = arp;
  std::cout << (*ppa)->year << std::endl;
  std::cout << (*(ppb+1)) ->year << std::endl;
  return 0;
}

模板类:vector: vector<typeName> vt(n_elem); 包含在 std中 需要添加<vector>头文件 堆中

模板类:array: array<typeName, n_elem> arr; 存储在栈中 <array> 

模板类的例子:

#include <iostream>
#include <vector>
#include <array>

int main()
{
  using namespace std;
  double a1[4] = {1.2, 2.4, 3.6, 4.8};
  vector<double> a2(4);
  a2[0] = 1.0/3.0;
  a2[1] = 1.0 /5.0;
  a2[2] = 1.0/7.0;
  a2[3] = 1.0/9.0;

  array<double, 4> a3 = {3.14, 2.72, 1.62, 1.41};
  array<double, 4>a4;
  a4 = a3;
  
  cout << "a1[2]: " << a1[2] << " at " << &a1[2] << endl;
  cout << "a1[1]: " << a1[1] << " at " << &a1[1] << endl;
  cout << "a1[0]: " << a1[0] << " at " << &a1[0] << endl;
// 用-4 然后就到了 a3的内存地址中去了
  cout << "a1[-4]: " << a1[-4] << " at " << &a1[-4] << endl;
  cout << "a2[2]: " << a2[2] << " at " << &a2[2] << endl;
  cout << "a3[2]: " << a3[2] << " at " << &a3[2] << endl;
  cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl;

  a1[-2] = 20.2;
  cout << "a1[-2]: " << a1[-2] << " at " << &a1[-2] << endl;
  cout << "a3[2]: " << a3[2] << " at " << &a3[2] << endl;
  cout << "a4[2]: " << a4[2] << " at " << &a4[2] <<endl;

  return 0; 
}

第四章完结。 明天开始学第五章 

猜你喜欢

转载自blog.csdn.net/soulwyb/article/details/89449909