Pointers on C——8 Arrays.8

来源:互联网 发布:35是不是质数的算法 编辑:程序博客网 时间:2024/06/01 09:10

8.1.5 Arrays and Pointers

Pointers and arrays are not equivalent. To illustrate this idea, consider these declarations:

指针和数组并不是相等的。为了说明这个概念,请考虑下面这两个声明:


int a[5];

int *b;


Can a and b be used interchangeably? Both have pointer values, and you can use indirection and subscripts on either one. They are, nevertheless, quite different.

a 和b 能够互换使用吗?它们都具有指针值,它们都可以进行间接访问和下标引用操作。但是,它们还是存在相当大的区别。


Declaring an array sets aside space in memory for the indicated number of elements, and then creates the array name whose value is a constant that points to the beginning of this space. Declaring a pointer variable reserves space for the pointer itself, but that is all. Space is not allocated for any integers. Furthermore, the pointer variable is not initialized to point to any existing space. If it is an automatic variable it is not initialized at all. These two declarations look very different when diagrammed.

声明一个数组时,编译器将根据声明所指定的元素数量为数组保留内存空间,然后再创建数组名,它的值是一个常量,指向这段空间的起始位置。声明一个指针变量时,编译器只为指针本身保留内存空间,它并不为任何整型值分配内存空间。而且,指针变量并未被初始化为指向任何现有的内存空间,如果它是一个自动变量,它甚至根本不会被初始化。把这两个声明用图的方法来表示,你可以发现它们之间存在显著不同。


Thus, after the declarations the expression *a is perfectly legal, but the expression *b is not. *b will access some indeterminate location in memory or cause the program to terminate. On the other hand, the expression b++ will compile, but a++will not because the value of a is a constant.

因此,上述声明之后,表达式与是完全合法的,但表达式*b 却是非法的。*b 将访问内存中某个不确定的位置,或者导致程序终止。另一方面,表达式b++可以通过编译,但a++却不行,因为a的值是个常量。


It is important that you understand this distinction clearly, because the next topic may muddy the waters.

你必须清楚地理解它们之间的区别,这是非常重要的,因为我们所讨论的下一个话题有可能把水搅浑。


上一章 Pointers on C——8 Arrays.7