Académique Documents
Professionnel Documents
Culture Documents
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).
where size is the number of elements that the array can store, this is always an (unsigned) integer. For example:
double x_data[100];
http://www.phy225.dept.shef.ac.uk/mediawiki/index.php/Arrays,_dynamic_array_allocation
1/9
14/2/2014
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;
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];
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
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;
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
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i;
int* i_array;
int j;
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;
}
4/9
14/2/2014
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);
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;
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
#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;
}
alternatively, the array type name and size can be given, e.g.
double average(double data_array[9], 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
#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
}
// all done, close files
fclose(infile1);
fclose(infile2);
fclose(outfile);
system("pause");
return 0;
}
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
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);
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
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"
http://www.phy225.dept.shef.ac.uk/mediawiki/index.php/Arrays,_dynamic_array_allocation
9/9