RAD Studio
ContentsIndex
PreviousUpNext
Arrays

The declaration 

type declarator [<constant-expression>] 

declares an array composed of elements of type. An array consists of a contiguous region of storage exactly large enough to hold all of its elements. 

If an expression is given in an array declarator, it must evaluate to a positive constant integer. The value is the number of elements in the array. Each of the elements of an array is numbered from 0 through the number of elements minus one. 

Multidimensional arrays are constructed by declaring arrays of array type. The following example shows one way to declare a two-dimensional array. The implementation is for three rows and five columns but it can be very easily modified to accept run-time user input. 

 

/* DYNAMIC MEMORY ALLOCATION FOR A MULTIDIMENSIONAL OBJECT. */
#include <stdio.h>
#include <stdlib.h>

 

typedef long double TYPE;
typedef TYPE *OBJECT;
unsigned int rows = 3, columns = 5;

 

void de_allocate(OBJECT);

 

int main(void) {
  OBJECT matrix;
  unsigned int i, j;

 

  /* STEP 1: SET UP THE ROWS. */
  matrix = (OBJECT) calloc( rows, sizeof(TYPE *));

 

  /* STEP 2: SET UP THE COLUMNS. */
  for (i = 0; i < rows; ++i)
    matrix[i] = (TYPE *) calloc( columns, sizeof(TYPE));

 

    for (i = 0; i < rows; i++)
      for (j = 0; j < columns; j++)
        matrix[i][j] = i + j;    /* INITIALIZE */

 

  for (i = 0; i < rows; ++i) {
    printf("\n\n");
    for (j = 0; j < columns; ++j)
      printf("%5.2Lf", matrix[i][j]);
  de_allocate(matrix);
  return 0;
  }

 

void de_allocate(OBJECT x) {
  int i;

 

  for (i = 0; i < rows; i++)    /* STEP 1: DELETE THE COLUMNS */
    free(x[i]);

 

  free(x);    /* STEP 2: DELETE THE ROWS. */
  }

This code produces the following output:

0.00 1.00 2.00 3.00 4.00
1.00 2.00 3.00 4.00 5.00
2.00 3.00 4.00 5.00 6.00

In certain contexts, the first array declarator of a series might have no expression inside the brackets. Such an array is of indeterminate size. This is legitimate in contexts where the size of the array is not needed to reserve space. 

For example, an extern declaration of an array object does not need the exact dimension of the array; neither does an array function parameter. As a special extension to ANSI C, CodeGear C++ also allows an array of indeterminate size as the final member of a structure. Such an array does not increase the size of the structure, except that padding can be added to ensure that the array is properly aligned. These structures are normally used in dynamic allocation, and the size of the actual array needed must be explicitly added to the size of the structure in order to properly reserve space. 

Except when it is the operand of a sizeof or & operator, an array type expression is converted to a pointer to the first element of the array.

Arrays

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!