【问题标题】:How can I check if a struct contains any data as I'm looping passed it?我如何检查结构是否包含任何数据,因为我正在循环传递它?
【发布时间】:2018-09-12 18:38:57
【问题描述】:

我正在尝试遍历已经为它们动态分配内存的 2D 结构数组,并识别任何没有来自用户输入的数据的结构。 换句话说,我要求用户使用数组选择特定点来存储他们的数据,然后我想遍历数组,打印其中的所有内容,并为没有保存数据的点显示 EMPTY。

当我在循环中传递结构时,如何确定结构是否包含数据?

typedef struct item {
    char name[20];
    int quantity;
} item;

struct item **shelves = (item **)malloc(num_rows * sizeof(item *));
for (i = 0; i < num_rows; i++) {
    shelves[i] = (item *)malloc(num_cols * sizeof(item));
}

for (int i = 0; i < num_rows; i++) {
    for (int j = 0; j < num_cols; j++) {
            ???     
    }               
}

【问题讨论】:

  • 在结构中添加标志bool empty;
  • char empty C 中没有bool 类型:p
  • @Avert 您的信息已过时。大约十年左右..
  • @Mayur 只有在有其他成员也可以使用位字段时才会节省内存,这似乎不是这里的情况。
  • ..不是说这很可能是一个非常不成熟的优化。

标签: c multidimensional-array struct


【解决方案1】:

添加一个标志来标记使用/空结构。

从 C99 开始就有使用 #include 的 bool 类型

【讨论】:

    【解决方案2】:

    为你的结构item添加一个标志,当用户为其指定数据时,然后设置标志。您可以像这样使用bool

    typedef struct item {
        char name[20];
        int quantity;
        bool used;
    } item;
    

    或者你也可以使用位域:

    typedef struct item {
        char name[20];
        int quantity;
        unsigned char used:1; //bitfield
    } item;
    

    无论哪种方式,将used 成员设置为1(或true,如果它是bool),然后在打印结构数组时检查它。

    for (int i = 0; i < num_rows; i++) {
        for (int j = 0; j < num_cols; j++) {
                if(shelves[i][j].used){
                    //printf statement for struct goes here
                }
                else{
                    //printf statement for EMPTY goes here
                }
        }               
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-13
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多