Download Learning GNU C - Non-GNU

Transcript
Chapter 6: Structured Data Types
29
To get around this inconvenience, a GNU extension to the C language allows you to
initialise array elements selectively by number. When initialised by number, the elements
can be placed in any order withing the curly braces preceded by [index]=value. Like so:
initialise array.c
#include <stdio.h>
int
main()
{
int i;
int first_array[100] = { [90]=4, [0]=5, [98]=6 };
double second_array[5] = { [3] = 1.01, [4] = 1.02 };
printf ("sure enough, first_array[90] == %d\n\n", first_array[90]);
printf ("sure enough, first_array[99] == %d\n\n", first_array[99]);
for (i = 0; i < 5; i++)
printf ("value of second_array[%d] is %f\n", i, second_array[i]);
return 0;
}
6.5 Multidimensional Arrays
The array we used in the last example was a one dimensional array. Arrays can have more
than one dimension, these arrays-of-arrays are called multidimensional arrays. They are
very similar to standard arrays with the exception that they have multiple sets of square
brackets after the array identifier. A two dimensional array can be though of as a grid of
rows and columns.
number square.c
#include <stdio.h>
const int num_rows = 7;
const int num_columns = 5;
int
main()
{
int box[num_rows][num_columns];
int row, column;
for (row = 0; row < num_rows; row++)
for (column = 0; column < num_columns; column++)
box[row][column] = column + (row * num_columns);
for (row = 0; row < num_rows; row++)
{
for(column = 0; column < num_columns; column++)
{
printf("%4d", box[row][column]);
}