如何设置结构数组的“结尾”

时间:2019-09-23 03:04:10

标签: c data-structures struct sentinel

我想将typedef struct { char * id; char * date; } ROW; int main(int argc, char *argv[]) { FILE * fp = fopen("test100k.csv", "r"); ROW * rows = malloc(sizeof(row) * 10000); int row_num = 0; ROW row; char buffer[255]; while(fgets(buffer, sizeof(buffer), fp) != NULL) { // some logic to set the object rows[row_num++] = row; } rows[row_num] = NULL; // how to do this? } 的等效项设置为结构数组的末尾,这样我就知道它何时结束。

到目前为止,我正在尝试执行以下操作:

{{1}}

“结束”行数组的正确方法是什么?

3 个答案:

答案 0 :(得分:0)

一种可能性是定义一个常量,该常量由其成员的唯一值用作标记​​:

#include <stdlib.h>
#include <stdio.h>

typedef struct {
    char * id;
    char * date;
} ROW;

/* Initialising the ROW's members below to a literal could lead to 
   ambiguities, as the compiler is free to merge the same literal 
   appearing more then once into only one instance in memory. 
   Whereas initialising the members to the struct's address itself 
   guarantees the uniqueness of the address stored.
   (Just do not ever dereference it, at least not without casting it 
   back to the type ROW.) */

const ROW STOPPER_ROW = {(char*)&STOPPER_ROW, (char*)&STOPPER_ROW};

int main(int argc, char *argv[]) {
    ...

    ROW * rows = malloc(10000 * sizeof *rows);
    size_t row_num = 0;
    ...

    while(NULL != fgets(buffer, sizeof(buffer), fp) && 
          10000 > row_num) {    
        // some logic to set the object
        rows[row_num++] = row;
    }

    rows[row_num] = STOPPER_ROW;

    row_num = 0;
    /* Comparing only one member below in fact would do. */
    while (rows[row_num].id != STOPPER_ROW.id && 
           rows[row_num].date != STOPPER_ROW.date)
    {
        /* Use rows[row_num] here */
        ++row_num;
    }
}

答案 1 :(得分:0)

这些是标准方法:

  • 添加一个计数器变量,该变量将指示最后一个有效索引。
  • 按引用而不是按值存储行。即,为每行分配一个空间并将其指针存储在数组中,而不是存储行本身。如果指针为空,则该行无效。
  • 如果某行有一个已知的无效值,请将所有数组单元初始化为该值。无效值的单元格将指示有效项的结束。

答案 2 :(得分:-2)

您可以尝试使用memset:

docker.compose