Introduction to Programming and C++

Contents Previous Topic Next Topic

Consider Program 1 which, rather than printing a[0], it simply prints a.

Program 1. Printing the variable of an array.

#include <iostream>

using namespace std;

int main() {
	const int N = 5;
	int a[N];

	cout << "The array is " << a << endl;
	cout << "The address of the first entry of the array is " << &( a[0] ) << endl;

	return 0;
}

If you look at the output, you will see that it looks a lot like the output from printing a pointer. If we print the address of each of the entries of the array, we get an idea of how they are stored. This is shown in Program 2 which first prints the array and then uses a for loop to print the address of each of the actual values.

Program 2. Printing the address of each entry of an array.

#include <iostream>

using namespace std;

int main() {
	const int N = 5;
	int a[N] = {01, 23, 45, 67, 89};

	cout << "The array is " << a << endl;

	for ( int i = 0; i < N; ++i ) {
		cout << "The address of entry a[" << i << "] is "
		     << &( a[i] ) << endl;
	}

	return 0;
}

If I run this on ecelinux, I get:

The array is 0xffbefb00
The address of entry a[0] is 0xffbefb00
The address of entry a[1] is 0xffbefb04
The address of entry a[2] is 0xffbefb08
The address of entry a[3] is 0xffbefb0c
The address of entry a[4] is 0xffbefb10

Note that the value stored by the array variable and the address of a[0] are equal. Each subsequent array entry is located at an address which is four bytes further (four bytes being the size of an array). This means that 5 × 4 bytes = 20 bytes have been set aside for this array. The actual storage would appear as shown in Figure 1.

Figure 1. Storage associated with the array a[5] in Program 1.

You may note that 1 = 116, 23 = 1716, 45 = 2D16, 67 = 4316, and 89 = 5916, and as each int occupies 4 bytes, this results in 00000001, etc.


Questions

1. Create a program which has three arrays int a[2], int b[4] and int c{7], defined in that order. Print out the values of a, b, and c, and try to determine how they are stored in main memory.

2. How much memory is needed to store the array double a[1024]? Write a program which prints the value of a and from this, determine where a[0], a[1], and a[1023] are stored. Verify this with your program.

3. What are the addresses of b[0] and b[8] of the boolean array bool b[16]? Suggest an approach which uses one eighth of the memory used by this array.

4. Create an array of pointers to int: int * ptrs[4]. Create an array int a[4] = {1, 2, 3, 4} and assign the address of the four entries of a to the four entries of ptrs. Now replace each entry of a by its square but do so by accessing only ptrs.


Contents Previous Topic Top Next Topic