【问题标题】:Nulling array of structure in structure结构中结构的空数组
【发布时间】:2018-11-28 16:43:42
【问题描述】:

在我的程序中,我必须创建包含其他结构数组(即列表)的结构。

struct ListEl {
string text;
ListEl *next;
};
struct hashTable {
int size;
ListEl *tab;
};

主要我必须清空“标签”的所有元素,但我无法这样做:

hashTable *hashingTable;
hashingTable->size = 256;
hashingTable->tab = new ListEl[hashingTable->size];

for (int i = 0; i < 256; i++) {

    hashingTable->tab[i] = NULL; //<--------------Cannot do that
}

在这个 for 循环中,我从编译器收到一个错误:no operator"=" 与这些操作参数不匹配,请键入操作数 "ListEl = int"。 我做错了什么?

同时我可以做到:

struct ListEl {
string text;
ListEl *next;
};


int main(){
    ListEl *tab[256];
     for (int i = 0; i < 256; i++) {
        tab[i] = NULL;
   }
} 

有什么不同?

【问题讨论】:

  • 为什么不使用 memset 将所有值设置为零。看看我的回答。使用将 NULL 分配给不允许的结构。您只能对指针进行 NULL 赋值。
  • 谢谢!那么我将如何使用 NULL 来做到这一点?

标签: c++ data-structures struct


【解决方案1】:

我建议你使用构造函数来初始化hashTableListE1。 可能是这样的:

struct ListEl
{
  string text;
  ListEl *next;

  ListE1(){text = ""; next = NULL;}
};

struct hashTable
{
  int size;
  ListEl *tab;

  hashTable(int n){size = n;tab = new List[n];}
};

然后你可以简单地初始化它:

hashTable* hashingTable = new hashTable(256); 

【讨论】:

    【解决方案2】:

    不必初始化数组成员。该结构有一个隐式构造函数,它将所有字段设置为 0。

    因此,当您使用new ListEl[hashingTable-&gt;size] 创建数组时,数组的每个成员都是使用此默认构造函数构造的。

    您确实遇到的一个问题是没有初始化hashingTable。您取消引用此指针而不给它一个值。这会调用undefined behavior

    你可以使用new给它一个值:

    hashTable *hashingTable = new hashTable;
    

    编辑:

    隐式定义的构造函数不会显式初始化原始对象(如指针或整数类型)的成员,但会初始化类对象的成员。您需要显式定义一个构造函数来初始化 next 成员:

    struct ListEl {
        string text;
        ListEl *next;
        ListEl():text(),next(NULL) {}
    };
    struct hashTable {
        int size;
        ListEl *tab;
        hashTable:size(0),tab(NULL) {}
    };
    

    【讨论】:

    • @Michał 很高兴我能帮上忙。如果您觉得有用,请随时 accept this answer
    【解决方案3】:

    memset() 可用于将列表中的所有值设置为 NULL。

    #include <iostream>
    #include <cstring>
    
    using namespace std;
    
    struct ListEl
    {
      string text;
      ListEl *next;
    };
    struct hashTable
    {
      int size;
      ListEl *tab;
    };
    
    main ()
    {
    
      hashTable *hashingTable;
      hashingTable->size = 256;
      hashingTable->tab = new ListEl[hashingTable->size];
    
    /*  for (int i = 0; i < 256; i++)
        {
          hashingTable->tab[i] = NULL;  //<--------------Cannot do that
        }
        */
        memset(hashingTable->tab,0,(hashingTable->size * sizeof(ListEl)));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多