c 语言数组的基本用法,详解C++编程中数组的基本用法

这篇博客介绍了C++中数组的基本操作,包括通过下标访问元素,多维数组的使用,以及数组初始化。文中强调了数组名在表达式中会转换为指向首元素的指针,并展示了如何通过指针访问数组的不同部分。此外,还讨论了类数组成员的初始化,特别是当类具有构造函数时,以及静态成员数组的初始化方法。
摘要由CSDN通过智能技术生成

可以使用数组下标操作符 ([ ]) 访问数组的各个元素。 如果在无下标表达式中使用一维数组,组名计算为指向该数组中的第一个元素的指针。

// using_arrays.cpp

int main() {

char chArray[10];

char *pch = chArray; // Evaluates to a pointer to the first element.

char ch = chArray[0]; // Evaluates to the value of the first element.

ch = chArray[3]; // Evaluates to the value of the fourth element.

}

使用多维数组时,在表达式中使用各种组合。

// using_arrays_2.cpp

// compile with: /EHsc /W1

#include

using namespace std;

int main() {

double multi[4][4][3]; // Declare the array.

double (*p2multi)[3];

double (*p1multi);

cout << multi[3][2][2] << "\n"; // C4700 Use three subscripts.

p2multi = multi[3]; // Make p2multi point to

// fourth "plane" of multi.

p1multi = multi[3][2]; // Make p1multi point to

// fourth plane, third row

// of multi.

}

在前面的代码中, multi 是类型 double 的一个三维数组。 p2multi 指针指向大小为三的 double 类型数组。 本例中该数组用于一个,两个和三个下标。 尽管指定所有下标更为常见(如 cout 语句所示),但是如下的语句 cout 所示,有时其在选择数组元素的特定子集时非常有用。

初始化数组如果类具有构造函数,该类的数组将由构造函数初始化。如果初始值设定项列表中的项少于数组中的元素,则默认的构造函数将用于剩余元素。如果没有为类定义默认构造函数,初始值设定项列表必须完整,即数组中的每个元素都必须有一个初始值设定项。

考虑定义了两个构造函数的Point 类:

// initializing_arrays1.cpp

class Point

{

public:

Point() // Default constructor.

{

}

Point( int, int ) // Construct from two ints

{

}

};

// An array of Point objects can be declared as follows:

Point aPoint[3] = {

Point( 3, 3 ) // Use int, int constructor.

};

int main()

{

}

aPoint 的第一个元素是使用构造函数 Point( int, int ) 构造的;剩余的两个元素是使用默认构造函数构造的。

静态成员数组(是否为 const)可在其定义中进行初始化(类声明的外部)。例如:

// initializing_arrays2.cpp

class WindowColors

{

public:

static const char *rgszWindowPartList[7];

};

const char *WindowColors::rgszWindowPartList[7] = {

"Active Title Bar", "Inactive Title Bar", "Title Bar Text",

"Menu Bar", "Menu Bar Text", "Window Background", "Frame" };

int main()

{

}

表达式中的数组当数组类型的标识符出现在 sizeof、address-of (&) 或引用的初始化以外的表达式中时,该标识符将转换为指向第一个数组元素的指针。 例如:

char szError1[] = "Error: Disk drive not ready.";

char *psz = szError1;

指针 psz 指向数组 szError1 的第一个元素。 请注意,与指针不同,数组不是可修改的左值。 因此,以下赋值是非法的:

szError1 = psz;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值