Lecture - 2 (Static Dynamic Arrays)
Lecture - 2 (Static Dynamic Arrays)
Lecture : 04
main()
{
int x[6];
int j;
for(j = 0; j < 6; j++)
//We have declared an int array of six
x[j] = 2 * j; elements and initialized it in the loop.
}
Sunday, April 28, 2024 3
Arrays
Let’s revise some of the array concepts:
Array declaration: int x[6]; or float x[6]; or double x[6];
An array is collection of cells of the same type.
We can only store integers in this array. We cannot put int in first location,
float in second location and double in third location.
Its individual items are numbered from zero to one less than array size.
The reason is the name x is not lvalue and we cannot assign any value
to it. For understanding purposes, consider x as a constant. Its name
or memory location can not be changed. This is a collective name for
six locations. We can access these locations as x[0], x[1] up to x[5].
You find out when the program executes that you need an integer
array of size n=20.
On finding it, the computer will give the address of first location to the
programmer which will be stored in y.
When we said int* y = new int[20]; the new returns the memory
address of first of the twenty locations and we store that address into
y. As y is a pointer variable so it can be used on the left-hand side. We
can write it as:
y = &x[0];
y = x;
We would not do this to the x array because we did not use new
to create it.
foo = &myvar;
◦ myvar = 25;
◦ foo = &myvar;
◦ bar = myvar;
The values contained in each variable after the execution of this are
shown in the following diagram:
Reference operator (&)
The second statement assigns foo the address of myvar, which we have
assumed to be 1776.
Finally, the third statement, assigns the value contained in myvar to bar. This
is a standard assignment operation, as already done many times earlier.
The main difference between the second and third statements is the
appearance of the reference operator (&).
Dereference operator (*)
The variable that stores the address of another variable (like foo in the
previous example) is what in C++ is called a pointer. Pointers are a
very powerful feature of the language that has many uses in lower
level programming.
baz = *foo;
This could be read as: "baz equal to value pointed to by foo", and the
statement would actually assign the value25 to baz, since foo is 1776,
and the value pointed to by 1776 (following the example above)
would be 25.
Dereference operator (*)
myvar = 25;
foo = &myvar;
myvar == 25
&myvar == 1776
foo == 1776
*foo == 25
Declaring Pointer Variables
The value of a pointer variable is an address. That is the value refers to
another memory space. The data is typically stored in this memory
space. Therefore when you declare a pointer variable, you also specify
the data type of the value to be stored in the memory location to
which the pointer variable points.