天天看點

Pointers on C——8 Arrays.12

8.1.9 Incomplete Initialization

What happens with these two declarations?

在下面兩個聲明中會發生什麼情況呢?

int vector[5] = { 1, 2, 3, 4, 5, 6 };

int vector[5] = { 1, 2, 3, 4 };

In both cases, the number of initializers does not match the size of the array. The first declaration is an error; there is no way to pack six integer values into five integer variables. The second, however, is legal. It provides values for the first four elements of the array; the last element is initialized to zero.

在這兩種情況下,初始化值的數目和數組元素的數目并不比對。第1 個聲明是錯誤的,我們沒有辦法把6 個整型值裝到5 個整型變量中。但是,第2 個聲明卻是合法的,它為數組的前4 個元素提供了初始值,最後一個元素則初始化為0 。

Can the middle values be omitted from the list as well?

那麼,我們可不可以省略清單中間的那些值呢?

int vector[5] = { 1, 5 };

The compiler can only tell that there are not enough initializers, but it has no way to figure out which ones are missing. Therefore, only trailing initializers can be omitted.

編譯器隻知道初始值不夠,但它無法知道缺少的是哪些值。是以,隻允許省略最後幾個初始值。

8.1.10 Automatic Array Sizing

Here is an example of another useful technique.

這裡是另一個有用技巧的例子。

int vector[] = { 1, 2, 3, 4, 5 };

If the array size is missing, the compiler makes the array just big enough to hold the initializers that were given. This technique is particularly helpful if the initializer list is frequently modified.

如果聲明中并未給出數組的長度,編譯器就把數組的長度設定為剛好能夠容納所有的初始值的長度。如果初始值清單經常修改,這個技巧尤其有用。

8.1.11 Character Array Initialization

From what we have said so far, you might think that character arrays are initialized like this:

根據目前我們所學到的知識,你可能認為字元數組将以下面這種形式進行初始化:

char message[] = { 'H', 'e', 'l', 'l', 'o', 0 };

The code works, but it is cumbersome for all but the shortest strings. Therefore, the language Standard provides a shorthand notation for initializing character arrays:

這個方法當然可行。但除了非常短的字元串,這種方法确實很笨拙。是以,語言标準提供了一種快速方法用于初始化字元數組:

char message[] = "Hello";

Although this looks like a string literal, it is not. It is simply an alternate way of writing the initializer list in the previous example.

盡管它看上去像是一個字元串常量,實際上并不是。它隻是前例的初始化清單的另一種寫法。

How can you tell the difference between string literals and these shorthand initializer lists if they look exactly the same? They are distinguished from one another by the context in which theyʹre used. When initializing a character array, it is an initializer list. Everywhere else it is a string literal.

如果它們看上去完全相同,你如何分辨字元串常量和這種初始化清單快速記法呢?它們是根據它們所處的上下文環境進行區分的。當用于初始化一個字元數組時,它就是一個初始化清單。在其他任何地方,它都表示一個字元串常量。

Here is an example:

這裡有二個例子:

char message1[] = "Hello";

char *message2 = "Hello";

The initializers look alike, but they have different meanings. The first initializes the elements of a character array, but the second is a true siring literal. The pointer variable is initialized to point to wherever the literal is stored, as illustrated below:

這兩個初始化看上去很像,但它們具有不同的含義。前者初始化一個字元數組的元素,而後者則是一個真正的字元串常量。這個指針變量被初始化為指向這個字元串常量的存儲位置,如下圖所示:

Pointers on C——8 Arrays.12

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