Archive

Archive for the ‘Pointers to structures’ Category

Pointers to structures

July 29th, 2010 c# No comments

Like any other type, structures can be pointed by its own type of pointers:
struct movies_t {
string title;
int year;
};

movies_t amovie;
movies_t * pmovie;
Here amovie is an object of structure type movies_t, and pmovie is a pointer to point to objects of structure type movies_t. So, the following code would also be valid:
pmovie = &amovie;
The value of the pointer pmovie would be assigned to a reference to the object amovie (its memory address).

We will now go with another example that includes pointers, which will serve to introduce a new operator: the arrow operator (->):

// pointers to structures
#include
#include
#include
using namespace std;

struct movies_t {
string title;
int year;
};

int main ()
{
string mystr;

movies_t amovie;
movies_t * pmovie;
pmovie = &amovie;

cout << "Enter title: ";
getline (cin, pmovie->title);
cout << "Enter year: ";
getline (cin, mystr);
(stringstream) mystr >> pmovie->year;

cout << "\nYou have entered:\n";
cout << pmovie->title;
cout << " (" << pmovie->year << ")\n";

return 0;
}

output:
Enter title: Invasion of the body snatchers
Enter year: 1978

You have entered:
Invasion of the body snatchers (1978)

The previous code includes an important introduction: the arrow operator (->). This is a dereference operator that is used exclusively with pointers to objects with members. This operator serves to access a member of an object to which we have a reference. In the example we used:

pmovie->title

Which is for all purposes equivalent to:

(*pmovie).title

Both expressions pmovie->title and (*pmovie).title are valid and both mean that we are evaluating the member title of the data structure pointed by a pointer called pmovie. It must be clearly differentiated from:

*pmovie.title

which is equivalent to:

*(pmovie.title)

Categories: Pointers to structures Tags: