Arrays of Pointers in C Plus Plus, Part 2

This tutorial introduces intermediate concepts and examples pertaining to Arrays of Pointers in C Plus Plus. It builds on the information presented in our basic tutorial, available here.

Our first code snippet introduces the syntax for declaring an array of pointers to structures. C++ (C Plus Plus) and also the original C language each support data structures, although C++ also includes support for classes, which can be thought of as data structures on steroids.

// Arrays of Pointers in C Plus Plus, Part 2
#include <iostream>
using namespace std;	// .Net needs this, gcc not so much

struct myStruct {
	int alpha;
	int delta;
	char gamma[10];
};
void main()
{
	myStruct zeta;
	myStruct myStructPointer[10];	
}

Review of the above code

Let us take a closer look at the previous code. Lines 5 through 9 illustrate a technique for defining a user-defined data type, also referred to as a structure or a UDT. Native data types should be familiar to C++ (C Plus Plus) programmers; int, float, char, double, and long are common types that are 'built-in' to the language. For better or worse, the world cannot be modeled with such simple types. It often becomes useful to logically group the native types into structures. Structures are easier to manipulate as a single entity, making programming more efficient and readable.

Our structure, myStruct, consists of three members; two integers and a char array. The members behave precisely as they would behave outside the context of a structure. The structure simply provides a convenient container for syntactically grouping data items that are logically related.

Line 12 declares an instance of the structure. This line of code actually causes space to be allocated for the two integers and the char array. We could print the size of the structure with a simple cout statement:

// Print the number of bytes allocated to zeta
cout << sizeof(zeta);

Line 13 declares an array of pointers. Each element of the array is a memory address that ostensibly contains the beginning of a data structure of type myStruct. Therefore, we have declared 10 pointers to structs.

We will deviate from the topic of pointers for a few sentences. It is important to note that the array elements are uninitialized. While C++ does not support the concept of an empty array, the language does not prevent us from creating an array without knowing what's actually stored there. Because the array is declared as a local variable (it's declared inside the function main() ), the 10 elements will be populated with whatever happens to be in memory when the program executes. This should not be construed as a programming error; we may assume that the programmer will initialize the array elements properly elsewhere in the main() function.

Returning to the topic at hand, please refer to the following code.

// Arrays of Pointers in C Plus Plus, Part 2
#include <iostream>
using namespace std;	// .Net needs this, gcc not so much

struct myStruct {
	int alpha;
	int delta;
	char gamma[10];
};
void main()
{
	myStruct zeta;
	myStruct myStructPointer[10];	

	myStructPointer[0] = &myStruct;
}

Line 15 initializes the first element of the array of structs. Element [0] receives the address of myStruct. Note the use of the '&' operator, which may be pronounced as "address of". We may read the entire statement as

"myStructPointer sub zero equals the address of myStruct"

Let us continue to modify our example program. Refer to the following code.

// Arrays of Pointers in C Plus Plus, Part 2
#include <iostream>
using namespace std;	// .Net needs this, gcc not so much

struct myStruct {
	int alpha;
	int delta;
	char gamma[10];
};
void main()
{
	myStruct zeta;
	myStruct myStructPointer[10];	

	myStructPointer[0] = &myStruct;

//	These two lines of code accomplish the same thing
	myStructPointer[0]->alpha = 42;
	myStruct.alpha = 42;
	
}

Line 18 demonstrates the syntax for accessing specific members of the structure that is 'pointed to' by myStructPointer[0]. Instead of using the dot operator to call out a structure member, we use the structure dereference operator, '->'. Lines 18 and 19 have the same effect. Both lines of code store the value 42 in the same memory location. Line 18 uses pointer notation and line 19 uses basic structure notation.

Potential problems with arrays of pointers in C Plus Plus

C++ presents powerful opportunities for introducing programming errors. In the following code snippet we illustrate a potential problem. After the code snippet we discuss the problem.

// Arrays of Pointers in C Plus Plus, Part 2
#include <iostream>
using namespace std;	// .Net needs this, gcc not so much

struct myStruct {
	int alpha;
	int delta;
	char gamma[10];
};
void main()
{
	myStruct zeta;
	myStruct myStructPointer[10];	

	myStructPointer[0] = &myStruct;

//	These two lines of code accomplish the same thing
	myStructPointer[0]->alpha = 42;
	myStruct.alpha = 42;

//      This will compile, but a logic error is lurking	
	int epsilon;
	myStructPointer[1] = (myStruct *)&epsilon; // oops
	myStructPointer[1]->delta = 100; // could be very bad
}

The previous code snippet includes a serious problem that may not manifest immediately. Line 22 declares a relatively harmless integer called epsilon. Line 23 stores the address of epsilon in the second element of the pointer array. The format of a pointer to a integer is identical to the format of a pointer to a structure; actually all pointers look the same at the CPU level. Unfortunately the pointer that we stored only points to 4 bytes of allocated space (we are assuming 4 byte integers, which is a common size). Our structure is at least 18 bytes wide. Line 24 attempts to defererence the pointer as a pointer to a structure of type myStruct. The dereference will succeed, but the value 100 will be stored at a location that is beyond the space allocated for epsilon. In other words, line 24 will clobber 4 bytes of data. Those 4 bytes may or may not be crucial to the execution of the program, but that status can't be determined until execution takes place. Depending on the structure of the executable program and the code path that was followed, the program may actually execute differently on different computers. The program may run properly for years, until a certain code path is taken and the 4 bytes being clobbered suddenly become necessary. These types of pointer problems are extremely challenging to debug.

Conclusion

Arrays of pointer to structures are useful tools but also require great care. Pointer errors are problematic to debug and may not surface the first time a program is executed.

More by this Author


Comments 5 comments

NNazir profile image

NNazir 6 years ago from Pakistan

I m glad to c a hub on c++....Thank you


Sandyspider profile image

Sandyspider 6 years ago from Wisconsin, USA

I'm just learning some of this. It is still foreign to me.


Mousumi Paul profile image

Mousumi Paul 5 years ago

I'm also glad to c hubs in C++..


Mousumi Paul profile image

Mousumi Paul 5 years ago

Good job


nicomp profile image

nicomp 5 years ago from Ohio, USA Author

Undeclared Identifier 89 minutes ago

"Nice tutorial...

See also free C++ source codes, exercises and competitons for beginners. "

@ Undeclared Identifier: If you insist on spamming me, please mix in a spell checker.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working