Guides:C/C Crash Course/Arrays

From CoderGuide

Jump to: navigation, search

Back to TOC

Arrays

We can also define an array of variables, either in one, two, three, or however many dimensions we wish. The way we do this is by adding brackets at the end of the name of a variable we're declaring. Inside the declaration, we give a number to tell the compiler how many elements are in this array. When we access an element of a variable, we start counting at zero. This means that, if you declare an array of 10 elements, you access all ten elements by using the numbers 0-9. It is very important you remember this as you write your programs to avoid a common mistake beginners make in working with arrays and pointers (pointers will be covered later).


Tricking a program to access elements of an array outside of the size declared by the program is a way crackers use to crack into computer systems. This is called a "buffer overrun attack." Basically, the attempt is to overwrite the binary instructions of a program by sending so much data, that the data overruns outside of the data space of a program, into the code space of a program. So yes, it is possible, however unlikely, to assign some values outside of an array, that will tell the computer to format your hard disk. Most likely, the computer will crash. Unix based systems such as Linux and Mac OS X generally will not crash completely if a program tries to access memory it shouldn't, and will not-so-gracefully kill the offending program before it can crash the entire system. Microsoft operating systems have typically been very bad about preventing system crashes.

/*****************
arrays.c
*****************/
main(){
        int a[10]; /*one dimensional array of 10 elements*/
        int b[10][5]; /*two dimensional array of 10 rows, and 5
                       columns-- a total of 50 elements*/
 
        a[0]=0; /* assign 0 to the first element in the array*/
        a[9]=5; /* assign 5 to the tenth element of the array*/
        b[2][3]=1; /*assign the 3rd row, 4th column, the value of 1*/
        a[3]=b[2][3]; /*assign the 4th element of a, with the value 
                        stored at the 3rd row and 4th column of b*/
 
        a[10]=10; /*BAD!!! Attempt to access the 11th element of 
                   a 10 element array will assign some value to
                   some location in memory that may be in use
                   by some other variable, or the machine
                   instructions themselves! */
 
}/** end main() **/

We can initialize an array when we create it, like so:

int array[10]={1,2,3,4,5,6,7,8,9,10};
 
int array2d[3,3]={
        1,2,3,
        1,2,3,
        1,2,3
};

We end the closed brace with a semicolon to mark the end of the variable definition. This ending semicolon is required because these braces are not marking a code block, they are just containing an initializer list.

Personal tools