Sunday 23rd of November 2008

Easy Structures In C++

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ... Posted on: April 3rd, 2008 by admin

When starting out with structures (data object template for data items) you can easily get confused. Therefore i’ve decided to post an easy way to do this. In short you create a typedef which makes a structure behave like an element such as int or bool.

For example:

typedef struct { int iOne; int iTwo; CString csOne; } str_mystructure;

This has created a structure type with three elements. You cannot define data in these elements as the memory hasnt been created yet. In order to do that you must instantiate by using the stack or heap. These can be done by ;

One the stack 

str_mystructure firstStructure = {1,2,”hello”};

On the heap;

str_mystructure* ptrFirstStructure = new str_mystructure;

If you use the heap then you must delete the memory when you are finished with it by using;

delete ptrFirstStructure;

If you dont delete the variable then the memory will be lost and you have your first memory leak.

This technique makes it easy to pass the data in functions. If you use the pointer to the data then you can not only change the data inside the function, but you are only passing the address not all the data. This means its faster at run time.

example;

myfunction(&firstStructure);

OR

myfunction(ptrFirstStructure);

Please feel free to ask any questions. Its not that hard :)

    Related posts

Leave a Reply

You must be logged in to post a comment.

Headlines

Feeds