简体   繁体   中英

Declaring C arrays

int array[5][3];

(obviously) creates a multi-dimensional C array of 5 by 3. However,

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

does not . I've always thought it would. What don't I understand about C arrays? If they only allow a constant to define the length of a C array, is there a way to get around this in some way?

In ANSI C (aka C89), all array dimensions must be compile-time integer constants (this excludes variables declared as const ). The one exception is that the first array dimension can be written as an empty set of brackets in certain contexts, such as function parameters, extern declarations, and initializations. For example:

// 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 added a new feature called variable-length arrays (VLAs), where the first dimension is allowed to be a non-constant, but only for arrays declared on the stack (ie those with automatic storage ). Global arrays (ie those with static storage ) cannot be VLAs. For example:

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];
}

Note that the latest edition of the C standard, C11, makes VLAs optional. Objective-C is based off of C99 and supports VLAs. C++ does not have VLAs, although many C/C++ compilers such as g++ which support VLAs in their C implementation also support VLAs in C++ as an extension.

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

Yes, it does. It's a C99 variable length array. Be sure to switch to C99 mode and be sure to have array declared at block or function scope. Variable length arrays cannot be declared at file scope.

Try:

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

As you said x has to be a constant or else think what would happen if in the middle of the program you changed the value of x,what would be the dimension of array:(

But by declaring it constan if you change the value of x you get a compile error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM