簡體   English   中英

聲明C數組

[英]Declaring C arrays

int array[5][3];

(顯然)創建了一個5 x 3的多維C數組。但是,

int x = 5;
int array[x][3];

沒有 我一直以為會。 我對C數組不了解? 如果它們僅允許常量定義C數組的長度,是否有某種方法可以解決此問題?

在ANSI C(aka C89)中,所有數組維都必須是編譯時整數常量(這不包括聲明為const變量)。 一個例外是,在某些情況下,例如函數參數, extern聲明和初始化,第一個數組維可以寫為空括號。 例如:

// The first parameter is a pointer to an array of char with 5 columns and an
// unknown number of rows.  It's equivalent to 'char (*array_param)[5]', i.e.
// "pointer to array 5 of char" (this only applies to function parameters).
void some_function(char array_param[][5])
{
    array_param[2][3] = 'c';  // Accesses the (2*5 + 3)rd element
}

// Declare a global 2D array with 5 columns and an unknown number of rows
extern char global_array[][5];

// Declare a 3x2 array.  The first dimension is determined by the number of
// initializer elements
int my_array[][2] = {{1, 2}, {3, 4}, {5, 6}};

C99添加了一個稱為可變長度數組 (VLA)的新功能,其中第一維允許為非恆定大小,但僅適用於在堆棧上聲明的數組(即具有自動存儲功能的數組)。 全局陣列(即具有靜態存儲的陣列)不能是VLA。 例如:

void some_function(int x)
{
    // Declare VLA on the stack with x rows and 5 columns.  If the allocation
    // fails because there's not enough stack space, the behavior is undefined.
    // You'll probably crash with a segmentation fault/access violation, but
    // when and where could be unpredictable.
    int my_vla[x][5];
}

請注意,最新版本的C標准C11使VLA成為可選。 Objective-C基於C99,並支持VLA。 C ++ 具有VLAS,盡管許多C / C ++編譯器,如克++支持VLAS在它們的C實現還支持VLAS在C ++中作為擴展。

 int x = 5;
 int array[x][3];

是的,它確實。 這是一個C99可變長度數組。 確保切換到C99模式,並確保在塊或函數作用域聲明了array 可變長度數組不能在文件范圍內聲明。

嘗試:

const int x=5;
int array[x][3];

正如您所說的x必須是常數,否則想想如果在程序中間更改x的值會發生什么,那將是array的維數:(

但是通過聲明它常量,如果您更改x的值,則會出現編譯錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM