0

If I create a structure in C++ like this:

typedef struct node {
    int item;
    int occurrency;
};

I know that a structure is allocated in memory using successive spaces, but what is the name of the structure (node in this example)? A simple way to give a name to the structure?

Pang
  • 9,564
  • 146
  • 81
  • 122
Overflowh
  • 1,103
  • 6
  • 18
  • 40
  • 2
    and why is the title "Pointer to a C++ structure"? The question has nothing to do with pointers. – Mr Lister Feb 16 '12 at 13:26
  • It's a data type, a special case of a `class` ... Not sure what you're after here. What does the way the `struct` is represented in memory have to do with the name of the concept? – unwind Feb 16 '12 at 13:21

3 Answers3

3

In C++ you don't have to use typedef to name a structure type:

struct node {
    int item;
    int occurrency;
};

is enough.

A pointer to an instance of that struct would be defined as node* mypointer;

E.g: You want to allocate a new instance with new:

node* mypointer = new node;
Constantinius
  • 34,183
  • 8
  • 77
  • 85
3

In C

struct node {
    int item;
    int occurrency;
};

is a tag, and by itself, it doesn't represent a type. That is why you cannot do

node n;

You have to do

struct node n;

So, to give it a "type name", many C programmers use a typedef

typedef struct node {
    int item;
    int occurrency;
} node;

That way you can do

node n;

Instead of

struct node n;

Also, you can omit the tag and do the following

typedef struct {
    int item;
    int occurrency;
} node;

However, in C++ this all changes, the typedef syntax is no longer needed. In C++ classes and structs are considered to be user-defined types by default, so you can just use the following

struct node {
    int item;
    int occurrency;
};

And declare nodes like this

node n;
Jesse Good
  • 50,901
  • 14
  • 124
  • 166
2

node is the name of the type. You can have multiple objects of that type:

struct node {
  int item;
  int occurrency;
};
node a;
node b;

In this example, both a and b have the same type (==node), which means that they have the same layout in memory. There's both an a.item and a b.item.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • Perfet, this is what I mean. In this case, what are a and b? A pointer? A null value? I think to have wrong my initial question... – Overflowh Feb 16 '12 at 17:51
  • @unNaturhal: They're both objects, i.e. areas of memory. `&a` would be a pointer to that area of memory. The objects are not initialized; you must write to them before you can read their values back. – MSalters Feb 17 '12 at 08:49
  • Please, could you draw me an example of memory allocation of a struct? I haven't understood `*a` which value gives back :/ – Overflowh Feb 17 '12 at 12:56
  • `*a` doesn't make sense. You'd better consult [our C++ book list](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – MSalters Feb 17 '12 at 15:49