Saturday, February 6, 2010

How to allocate memory for structure pointer using new operator in C++

1) Lets declares a structure.

struct Example_st
{
   int a;
   string b;
};
2) Declare a pointer of structure type Example_st, allocate memory and use it
..
/* Declare the structure pointer and assign it to NULL */
struct Example_st *struct_1 = NULL;

/* Allocate the memory using "new" */
struct_1 = new struct Example_st;
/* This statement allocates memory in the heap and assigns the starting
address to the structure pointer */

/* Access the structure members */
struct_1->a = 10;
strcpy(struct_1->b, "Allocate memory for structure pointer using new operator in C++");

PrintScreen(struct_1);

/* Remember to unallocate the memory allocated for the structure after using it */
delete struct_1;
..

0 comments:

Post a Comment

Recent Comments

About This Blog

Blog Archive

  © Blogger template Webnolia by Ourblogtemplates.com 2009

Back to TOP