Arrays?
Elementary data structure that exists as built-in in
most programming languages.
main( int argc, char** argv )
{
int x[6];
int j;
for(j=0; j < 6; j++)
x[j] = 2*j;
}
Arrays ?
§ Array declaration: int x[6];
§ An array is collection of cells of the same type.
§ The collection has the name ‘
x;
§ The cells are numbered with consecutive integers.
§ To access a cell, use the array name and an index:
x[0], x[1], x[2], x[3], x[4], x[5];
What is Array Name?
x is an array name but there is no variable x. ‘
x is not an
lvalue.
For example, if we have the code
int a, b;
then we can write
b = 2;
a = b;
a = 5;
But we cannot write
2 = a;
Array Name?
x’ is not an lvalue
int x[6];
int n;
x[0] = 5;
x[1] = 2;
x = 3; // not allowed
x = a + b; // not allowed
x = &n; // not allowed,
Dynamic Arrays?
You would like to use an array data structure but
you do not know the size of the array at compile
time.
. You find out when the program executes that you
need an integer array of size n=20.
§.Allocate an array using the new operator:
int* y = new int[20]; // or int* y = new int[n]
y[0] = 10;
y[1] = 15; // use is the same
.y is a lvalue; it is a pointer that holds the
address of 20 consecutive cells in memory.
. It can be assigned a value. The new operator
returns an address that is stored in y.
.We can write:
y = &x[0];
y = x; // x can appear on the right
// y gets the address of the
// first cell of the x array
We must free the memory we got using the new
operator once we are done with the y array.
delete[ ] y;
.We would not do this to the x array because we
did not use new to create it.
0 Comments