Skip to Content
C语言核心技术(原书第2版)
book

C语言核心技术(原书第2版)

by Peter Prinz, Tony Crawford
August 2017
Intermediate to advanced
798 pages
17h 44m
Chinese
China Machine Press
Content preview from C语言核心技术(原书第2版)
数组
|
131
数组
建这个长度可变数组。因此,在每次实例化时,数组都可以有不同的长度。然而,一旦
被创建,即便是长度可变数组,在它的当前存储周期内也不能改变数组长度。
动态对象被存储在栈中,当程序流离开对象所在的语句块时,动态对象的空间就会被释
放。因此,只有对小的、临时的数组,定义长度可变数组才比较合理。如想动态地创建
大型数组,通常应该使用标准函数
malloc()
和
calloc()
来显式地分配内存空间。这种数
组的存储周期会持续到程序结束,也可以调用函数
free()
来主动地释放被占用的内存空
间(请参见第
12
章)。
8.2 获取数组元素
下标运算符
[]
提供了一个简便的获取数组元素的方式,它利用索引(
index
)定位数组内
每个元素。如果
myArray
是一个数组的名称,并且
i
是一个整数,那么表达式
myArray[i]
指定了数组内索引为
i
的元素。数组元素的索引值从
0
开始。因此,长度为
len
的数组,其
索引值最大为
len-1
(请参见
5.2.7
节)。
下面程序的代码片段定义了数组
myArray
,并且给其中每个元素赋值:
#define A_SIZE 4
long myArray[A_SIZE];
for ( int i = 0; i < A_SIZE; ++i )
myArray[i] = 2 * i;
图
8-1
展示了赋值运算循环的结果。
图8-1:根据索引给数组元素赋值
数组索引值可以是任何所需的整数表达式。下标运算符
[]
不会检查索引的范围,因为
C
语言非常重视执行速度。程序员要确保索引值不会超出数组内存空间的边界。下面错误 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

算法精讲视频课程:24篇系列讲座

算法精讲视频课程:24篇系列讲座

罗伯特·塞奇威克, 凯文·韦恩(Kevin Wayne)

Publisher Resources

ISBN: 9787111562207