Homunculus Reticulli
Homunculus Reticulli

Reputation: 68366

Unfamiliar use of 'new' for memory allocation (C++)

I am working on some legacy code. I have the following data types:

typedef struct {

    char        *name ;

    ColumnType  type ;

    unsigned    pos ;    //column position in table

    CellData    **data ; //ptr to list of cells in column

}Column ;

struct _table {

    char name[TABLE_NAME_LEN+1] ;

    unsigned int num_rows ;

    unsigned int num_cols ;

    Column  **cols ; //ptr to list of columns

};



struct _table m_

In the source code, there is the following statement:

m_table.cols = new Column*[m_table.num_cols];

I am familiar with new[], but I'm no sure what the multiplication operator is doing there - can any explain?

Upvotes: 1

Views: 104

Answers (6)

tskuzzy
tskuzzy

Reputation: 36446

The * denotes a pointer. So you're creating an array of Column pointers.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 476840

It's not multiplication. The symbol * has many, many completely different meanings in C++, all depending on context.

In your case, you're creating a dynamic array of Column*, i.e. of pointers to Column.

In other words, you're saying new T[N];, where T = Column*.

Upvotes: 4

Mark Ransom
Mark Ransom

Reputation: 308061

It's not a multiplication operator, it's a pointer specification i.e. "pointer to Column".

Upvotes: 0

John Dibling
John Dibling

Reputation: 101446

It's not a multiplication operator. It's allocating an array of pointer-to-Column, rather than an array of Column.

Upvotes: 0

In your case Column* is a type (for pointers to instances of Column class) and you create an array of them.

Upvotes: 0

JaredPar
JaredPar

Reputation: 754505

It's not a multiplication operator. It's instead allocating an array of Column* (pointer to Column type). The resulting array stores pointer values

m_table.cols = new Column*[m_table.num_cols];
m_table.cols[0] = Column();  // Error: Expected Column* got Column
m_table.cols[0] = new Column();  // Ok

Upvotes: 3

Related Questions