Vous êtes sur la page 1sur 9

14/2/2014

Arrays, dynamic array allocation - Programming In C

Arrays, dynamic array allocation


From Programming In C
Table of contents
1 Introduction
2 Declaring and using arrays
2.1 One-dimensional arrays
2.1.1 Using array variables
2.1.2 Initializing arrays
2.2 Multidimensional arrays
2.2.1 Initialising multidimensional arrays
3 Dynamic array allocation (malloc method)
3.1 One-dimensional arrays
3.2 Multidimensional arrays
4 Dynamic array allocation (new method)
4.1 One-dimensional arrays
4.2 Multidimensional arrays
5 Pointers and Arrays
6 Arrays as function parameters
6.1 One-dimensional arrays
6.2 Multidimensional arrays
7 Array bound checking
8 Further Reading

Introduction
Imagine writing a program to analyse a data set of 1000 pairs of voltages and currents from an experiment to study
the electrical characteristics of some semiconductor device. You could declare enough double variables, v1, i1, v2,
i2, etc, but the program would at best be difficult to implement and debug. It would be much more convenient to
have some way of grouping together related variables. The most common way to achieve this in programming is
the array. An array is a series of objects, all of the same type, stored next to each other in memory. The array is
referred to by a single name and individual elements are accessed via an index (see below).

Declaring and using arrays


One-dimensional arrays
A one-dimensional array is declared as follows:
type array_name[size];

where size is the number of elements that the array can store, this is always an (unsigned) integer. For example:
double x_data[100];

declares an array called x_datathat stores 100 values of type double.

http://www.phy225.dept.shef.ac.uk/mediawiki/index.php/Arrays,_dynamic_array_allocation

1/9

14/2/2014

Arrays, dynamic array allocation - Programming In C

Using array variables


Array variables are used in much the same way as ordinary variables, but with an element number specified. In C
the number of array elements starts at 0. This means that the last element in the array x_datahas index number
99. The index of the required element is put in square brackets after the array variable's name. So to assign the
value 3.14159 to the seventh element of x_dataone would use:
x_data[6] = 3.14159;

Since the index can be specified by an integer variable this means that loops and related structures can be used to
access all the elements in an array. For instance a loop can be used to print out all the values stored in x_data
array defined above:
for (i=0;i<100;i++) printf("x_data[%d] = %lf\n", i, x_data[i]);

Initializing arrays
As with ordinary variables it is important to make sure that sensible start values are stored in an array before using
it. A loop is used initialise an array that has already been declared:
int array[5];
for (i=0;i<5;i++) array[i] = 0;

It is possible to declare and initialise an array at the same time:


int array[] = {1,3,2,9};

The compiler uses the number of items in the initialiser list, {...}, to determine the size of the array. Thus there is
no need for a number between the square brackets. In the example above an array of four integers is declared
(array[0]=1, array[1]=3, etc.)

Multidimensional arrays
A two dimensional array can be declared by specifying two sizes in brackets, e.g.
int matrix [5][10];

this creates an array of integers that is 5 row by 10 columns large.


To use such an array, both indices must be specified, e.g.:
matrix [2][3] = 13;

Arrays of 3 or more dimensions may be declared by using the required number of indices in the declaration.
C arrays are similar to matrices in mathematics. However, the index reference system starts from 0. Whilst this is
not really a problem it does mean that extra care should be taken when writing a computer program to implement
some matrix based piece of mathematics.

http://www.phy225.dept.shef.ac.uk/mediawiki/index.php/Arrays,_dynamic_array_allocation

2/9

14/2/2014

Arrays, dynamic array allocation - Programming In C

Initialising multidimensional arrays


The example below shows three different ways to initialise a 2-dimensional array using lists:
double data_array[2][2] = {1.0,2.0,3.0,4.0};
double data_array[2][2] = {{1.0,2.0},{3.0,4.0}};
double data_array[ ][2] = {{1.0,2.0},{3.0,4.0}};

If the first bracket set is empty then the compiler uses the number of inner brace pairs to define this dimension. All
the other dimensions must be specified explicitly. Extra sets of braces can be used to initialise lists for higher
dimensional arrays. All of the three statements above are equivalent to:
double data_array[2][2];
data_array[0][0] = 1.0;
data_array[0][1] = 2.0;
data_array[1][0] = 3.0;
data_array[1][1] = 4.0;

Dynamic array allocation (malloc method)


One-dimensional arrays
So far we have declared the number of elements in the array before executing the program. This is called compiletime allocation, and is fine if we know how many array elements there will be. However, usually the number of
array elements will be determined during the execution of the program. This is called run-time or dynamic memory
allocation. Pointers are required when using dynamic memory allocation.
An array is dynamically allocated in two stages: First a pointer of the correct type is declared:
type* array_name;

Next a block of memory of the required size is allocated using the malloc()function:
array_name = (type*) malloc(size);

where size is an integer corresponding to the number of bytes of memory required for the array. This size can be
obtained by using the sizeof()function which returns the number of bytes that a given variable type holds.
Having finished using the array, the memory must be emptied so that it can be re-used. This is done with the
free()function as follows:
free((void*) array_name);

If memory is not re-claimed after use, and more and more memory is dynamically reserved during run-time, then
there will be memory-leaks and run-time failures. The cast to void*prevents the pointer being accidentally
reused for some other purpose elsewhere in the program.
The functions malloc(), free()and sizeof()are provided by the header file stdlib.h
The following example illustrates how to dynamically declare and then use an array called i_arraythat stores a
number of integers that is specified by the user at run-time:

http://www.phy225.dept.shef.ac.uk/mediawiki/index.php/Arrays,_dynamic_array_allocation

3/9

14/2/2014

Arrays, dynamic array allocation - Programming In C

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i;
int* i_array;
int j;

// this will be the array

// find out how many integers are required


printf("How many integers? ");
scanf("%d",&i);
// Now allocate memory space
i_array = (int*)malloc(i*sizeof(int));
// code that uses the new array
for (j=0;j<i;j++)
{
i_array[j]=j;
printf("%d\n",i_array[j]);
}
free((void*) i_array);

// allocate storage for the array

// the pointer can be used as an array

// free up memory for reuse.

system("pause");
return 0;
}

Multidimensional arrays
The case of dynamically allocating a multidimensional array using the mallocmethod is a little more complicated.
A 2-dimensional array can be thought of as a "array of arrays", so first an array of pointers is made for the rows
and then each element of this array is, in turn, a pointer to an array which forms the columns of the 2D array. This
is best illustrated by the following example:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i,nrows,ncols;
// Define the size of the array at run time
printf("Enter number of rows and number of columns ");
scanf("%d %d",&nrows,&ncols);
int** array;
array=(int**)malloc(nrows*sizeof(int*));
for (i=0; i<nrows; i++)
array[i]=(int*)malloc(ncols*sizeof(int));
func(array, nrows, ncols); // some function that uses the array ....
for (i=0; i<nrows; i++)
free((void*)array[i]);
free((void*)array);
system("pause");
return 0;
}

Dynamic array allocation (new method)


http://www.phy225.dept.shef.ac.uk/mediawiki/index.php/Arrays,_dynamic_array_allocation

4/9

14/2/2014

Arrays, dynamic array allocation - Programming In C

One-dimensional arrays
C++ is an extension to the C programming language which introduces many powerful features, particularly that of
object oriented programming. All C commands form a subset of all C++ commands.
Dynamical array allocation in C++ is performed via a command called new. The syntax of the newcommand is
much more intuitive than the malloccommand which is why it is being introduced here even though it does not
technically form part of the C programming language.
The devcpp compiler permits array declaration via the newcommand, however the source file must be saved as
a C++ type source file (file extension .cpp) in order for newto work.
To change to the newsyntax requires, simply changing the malloccommand of the form
array_name = (type*) malloc(size);

to a command of the form


array_name = new type[size];

The definition of the array pointer and the freecommands remain the same.
The example above, dynamically creating a one-dimensional array called i_arrayvia the malloccommand is
repeated here using newinstead:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i;
int* i_array;
int j;

// this will be the array

// find out how many integers are required


printf("How many integers? ");
scanf("%d",&i);
// Now allocate memory space
i_array = new int[i];
// allocate storage for the array
// code that uses the new array
for (j=0;j<i;j++)
{
i_array[j]=j;
printf("%d\n",i_array[j]);
}
free((void*) i_array);

// the pointer can be used as an array

// free up memory for reuse.

system("pause");
return 0;
}

Multidimensional arrays
Multidimensional arrays can be dynamically allocated via the newmethod too. The following is an example of this
which shows the 2-dimensional array created in the mallocexample above being dynamically allocated using the
newmethod instead.
http://www.phy225.dept.shef.ac.uk/mediawiki/index.php/Arrays,_dynamic_array_allocation

5/9

14/2/2014

Arrays, dynamic array allocation - Programming In C

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i, nrows,cols;
// Define the size of the array at run time
printf("Enter number of rows and number of columns ");
scanf("%d %d",&nrows,&ncols);
int** array;
array=new int*[nrows];
for (i=0; i<nrows; i++)
array[i]=new int[ncols];
func(array, nrows, ncols); // some function that uses the array ....
for (i=0; i<nrows; i++)
free((void*)array[i]);
free((void*)array);
system("pause");
return 0;
}

Pointers and Arrays


Arrays and pointers are closely related in C. An array variable can be thought of as a pointer to the first element
of the array in the computer's memory, with the index giving the offset in memory for the various elements. Hence
the first element has an index of zero. Pointers and arrays are not exactly equivalent - a pointer variable can hold
different memory addresses. An array variable can only hold the address of the first element of the array.
Since the array variable is like a pointer there is no need to use the address-ofoperator (&) when using arrays
as function parameters.

Arrays as function parameters


One-dimensional arrays
It is possible to pass arrays of variables to functions. For one-dimensional arrays this is straightforward and any of
the following three techniques can be used for the function definition and the function prototype. First of all the
array type and array name can be given along with empty square parentheses, e.g.:
double average(double data_array[], int n);

alternatively, the array type name and size can be given, e.g.
double average(double data_array[9], int n);

Finally, the arrays can be passed as pointers as in:


double average(double *data_array, int n);

As an example of the usage of arrays with functions, a program to calculate the cross product of two vectors is
shown below:
http://www.phy225.dept.shef.ac.uk/mediawiki/index.php/Arrays,_dynamic_array_allocation

6/9

14/2/2014

Arrays, dynamic array allocation - Programming In C

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void cross (double v1[], double v2[], double vcross[]);
int main(void)
{
FILE *infile1, *infile2, *outfile;
double vec1[3], vec2[3], vec3[3];

// function prototype

// Open files and stop with error codes if this fails


if ((infile1=fopen("vector1.txt","r")) == NULL)
{
printf("Error: input file vector1.txt cannot be opened");
system("pause");
return 1;
}
if ((infile2=fopen("vector2.txt","r")) == NULL)
{
printf("Error: input file vector2.txt cannot be opened");
system("pause");
return 1;
}
if ((outfile=fopen("cross.txt","w")) == NULL)
{
printf("Error: output file cross.txt cannot be opened");
system("pause");
return 1;
}
// files have been opened so now read in data sets and call cross() function
while( (fscanf(infile1, "%lf%lf%lf", &vec1[0], &vec1[1], &vec1[2] ) > 0)
&& (fscanf(infile2, "%lf%lf%lf", &vec2[0], &vec2[1], &vec2[2] ) > 0) )
{
cross ( vec1, vec2, vec3 );
// call cross() function
fprintf(outfile,"%lf %lf %lf\n",vec3[0],vec3[1],vec3[2]);

// write results to file

}
// all done, close files
fclose(infile1);
fclose(infile2);
fclose(outfile);
system("pause");
return 0;
}

void cross (double v1[], double v2[], double vcross[])


{
// code to calculate cross products
vcross[0] = v1[1] * v2[2] - v1[2] * v2[1];
vcross[1] = v1[0] * v2[2] - v1[2] * v2[0];
vcross[2] = v1[0] * v2[1] - v1[1] * v2[0];
return;
}

Notes:
The function prototype and function definition could have the array dimensions inside the square brackets
The call to function cross has the names of the arrays ONLY, i.e. no brackets (this is important)
In this case function cross is of type void, see how such a function is called

http://www.phy225.dept.shef.ac.uk/mediawiki/index.php/Arrays,_dynamic_array_allocation

7/9

14/2/2014

Arrays, dynamic array allocation - Programming In C

In the above example, pointers could also be used to pass the three arrays to the function cross. In this case
void cross (double v1[], double v2[], double vcross[])

must be replaced by
void cross( double *v1, double *v2, double *v3)

in both the function definition and the function prototype. Nothing else needs changing (it is not necessary to use
the deferencing operator inside function crosswhen referring to the array variables).

Multidimensional arrays
For arrays with more than one dimension similar rules apply.
First of all the array type and array name can be given along with empty square parentheses, however, in this case
in the function prototype then the size of the upper dimensions must be specified in the function prototype:
double calc_array(double data_array[][3], int nrows, int ncols);

alternatively, the array type, name and dimension sizes can be explicitly given, e.g.:
double calc_array(double data_array[3][3], int nrows, int ncols);

Finally, the arrays can be passed via pointers, for a 2D array this would look like:
double calc_array(double **data_array, int nrows, int ncols);

Array bound checking


Unfortunately C programs do not check whether an array element that you access in some way lies within the
bounds of the array. This means that code like the following would be accepted by the compiler and will run:
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
int main(void)
{
int i;
int array[10]; // an array of ten integers
for (i=0;i<20;i++) array[i]=3*i; // store 20 values in the array
for(i=19;i>=0;i--) printf("%d\n",array[i]); // print out values in reverse order
system("pause");
return 0;
}

The for loop attempts to store 20 values in an array only large enough to store 10 values. This program will compile
on a lot of computer systems. The problem is that the extra memory used is not reserved and the computer's

http://www.phy225.dept.shef.ac.uk/mediawiki/index.php/Arrays,_dynamic_array_allocation

8/9

14/2/2014

Arrays, dynamic array allocation - Programming In C

operating system and/or the program itself can store other values in this memory space. Worse, data may already
be stored in this space before you overwrite it. This sort of programming error can be very difficult to trace and
you should take the utmost care to prevent it occurring.

Further Reading
Kelley and Pohl: Chapter 6, Arrays, Pointers, and Strings, pp 245-330.
http://en.wikibooks.org/wiki/C_Programming/Arrays
http://en.wikibooks.org/wiki/C_Programming/Pointers_and_arrays
http://en.wikibooks.org/wiki/C_Programming/Memory_management
http://en.wikibooks.org/wiki/C_Programming/Strings
Return to the course summary
Retrieved from "http://www.phy225.dept.shef.ac.uk/mediawiki/index.php/Arrays%2C_dynamic_array_allocation"

This page was last modified 10:17, 5 Dec 2011.

http://www.phy225.dept.shef.ac.uk/mediawiki/index.php/Arrays,_dynamic_array_allocation

9/9

Vous aimerez peut-être aussi