简体   繁体   English

不熟悉使用“ new”进行内存分配(C ++)

[英]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? 我对new []很熟悉,但是我不确定乘法运算符在做什么-可以解释吗?

It's not multiplication. 这不是乘法。 The symbol * has many, many completely different meanings in C++, all depending on context. 符号*在C ++中具有很多非常不同的含义,所有含义均取决于上下文。

In your case, you're creating a dynamic array of Column* , ie of pointers to Column . 在您的情况下,您正在创建Column*的动态数组,即指向Column的指针。

In other words, you're saying new T[N]; 换句话说,您是在说new T[N]; , where T = Column* . ,其中T = Column*

It's not a multiplication operator. 它不是乘法运算符。 It's instead allocating an array of Column* (pointer to Column type). 而是分配一个Column*数组(指向Column类型的指针)。 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

在您的情况下, Column*是一种类型(用于指向Column类实例的指针),然后创建它们的数组。

It's not a multiplication operator. 它不是乘法运算符。 It's allocating an array of pointer-to- Column , rather than an array of Column . 它分配的是指向Column的指针数组,而不是Column的数组。

它不是乘法运算符,它是一个指针规范,即“指向列的指针”。

The * denotes a pointer. *表示指针。 So you're creating an array of Column pointers. 因此,您正在创建一个Column指针数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM