c++ primer学习笔记(7)-数组

本文深入探讨了C++中数组的定义、使用及注意事项,包括数组的维数限制、初始化方式、字符数组特性以及数组下标访问等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.数组的定义

          // both buf_size and max_files are const
          const unsigned buf_size = 512, max_files = 20;
          int staff_size = 27;            // nonconst
          const unsigned sz = get_size();  // const value not known until run time
          char input_buffer[buf_size];     // ok: const variable
          string fileTable[max_files + 1]; // ok: constant expression
          double salaries[staff_size];     // error: non const variable
          int test_scores[get_size()];     // error: non const expression
          int vals[sz];                    // error: size not known until run time

注意点:

  1. 数组的维数必须是const的,对于这一点很诧异,第二条语句居然不通过,而第5条则可以,不知道编译器是怎么搞的
  2. 维数声明在变量后面,c#则在前面

2.显示初始化({})

const unsigned array_size = 3;
int ia[array_size] = {0, 1, 2};

3.特殊的字符数组

由于字符串非常常用,所以特殊一些

          char ca1[] = {'C', '+', '+'};                // no null
          char ca2[] = {'C', '+', '+', '\0'};         // explicit null
          char ca3[] = "C++";     // null terminator added automatically

注意:

  1. ca2和ca3是相同的,维数为4(注意数组不要超界) const char ch3[6] = "Daniel"; // error: Daniel is 7 elements
  2. 数组不可直接复制和赋值的
int ia[] = {0, 1, 2}; // ok: array of ints
int ia2[](ia);        // error: cannot initialize one array with another

int main()
{
    const unsigned array_size = 3;
    int ia3[array_size]; // ok: but elements are uninitialized!

    ia3 = ia;           //  error: cannot assign one array to another
    return 0;
}

4.数组下标访问

可用size_t来访问数组元素,而非数值

const size_t array_size = 10;
int ia[array_size]; // 10 ints, elements are uninitialized

// loop through array, assigning value of its index to each element
for (size_t ix = 0; ix != array_size; ++ix)
    ia[ix] = ix;

数组是很多数据结构的基础,长度不可变,较为底层,可用c++标准库中的一些高级数据结构来简化数组的操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值