Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Structure within itself?

I've been trying to port this code to python, but there is something I do not quite understand in C++ (I do know a bit of C++ but this is beyond me):

typedef struct huffnode_s
{
    struct huffnode_s *zero;
    struct huffnode_s *one;
    unsigned char val;
    float freq;
} huffnode_t;

What I don't get is how huffnode_s can be within itself, I've never seen this before and don't quite understand it. What does this mean, and if someone can, what would be the python equivalent?

like image 478
Douglas Avatar asked May 21 '10 20:05

Douglas


People also ask

Can a struct reference itself in C?

A structure can not refer itself directly. union VAL v; struct list * next; }; typedef struct list List; Creating lists...

Can a struct contain itself?

Pointers to structures Although a structure cannot contain an instance of its own type, it can can contain a pointer to another structure of its own type, or even to itself.

Can structure point to itself?

Self Referential structures are those structures that have one or more pointers which point to the same type of structure, as their member.

What is self referencing structure?

The self-referential structure is a structure that points to the same type of structure. It contains one or more pointers that ultimately point to the same structure. Structures are a user-defined data structure type in C and C++.


3 Answers

huffnode_s isn't within itself, only pointers to huffnode_s are in there. Since a pointer is of known size, it's no problem.

like image 136
Carl Norum Avatar answered Sep 22 '22 11:09

Carl Norum


This.

class Huffnode(object):
    def __init__(self, zero, one, val, freq):
        """zero and one are Huffnode's, val is a 'char' and freq is a float."""
        self.zero = zero
        self.one = one
        self.val = val
        self.freq = freq

You can then refactor your various C functions to be methods of this class.

Or maybe this.

from collections import namedtuple
Huffnode = namedtuple( 'Huffnode', [ 'zero', 'one', 'val', 'freq' ] )

If you want your C functions to remain functions.

That's it.

h0 = Huffnode(None, None, 'x', 0.0)
h1 = Huffnode(None, None, 'y', 1.0)
h2 = Huffnode(h0, h1, 'z', 2.0)

That's all that's required.

like image 42
S.Lott Avatar answered Sep 24 '22 11:09

S.Lott


it does not have a structure in itself. it has a pointer to that structure.

in memory struct huffnode_s would look like (32 bit machine):


|------------------ huffnode_s* zero - 4 bytes --------------|

|------------------ huffnode_s* one - 4 bytes----------------|

|unsigned char val - 1 byte + 3 bytes padding=======|

|------------------- float freq - 4 bytes -------------------------|


these sizes would vary machine to machine, and how it looks in memory is decided by compiler .

like image 22
Ramadheer Singh Avatar answered Sep 25 '22 11:09

Ramadheer Singh