清空结构中的结构数组

时间:2018-06-19 16:36:06

标签: c++ data-structures struct

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

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

在主要情况下,我必须将“ tab”的所有元素都为NULL,但是我无法这样做:

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;
   }
} 

有什么区别?

3 个答案:

答案 0 :(得分: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); 

答案 1 :(得分:0)

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)));
}

答案 2 :(得分:0)

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

因此,当您使用new ListEl[hashingTable->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) {}
};