在c中向数组添加struct元素的最佳方法?

在c中向数组添加struct元素的最佳方法?,c,C,我有一个这样的结构: typedef struct { char title[length]; char createdDate[length]; int completed; } Todo; typedef struct { int initialized; char title[length]; char createdDate[length]; int completed; } Todo; Todo todolist[100]

我有一个这样的结构:

typedef struct
{
    char title[length];
    char createdDate[length];
    int completed;
} Todo;

typedef struct
{
    int initialized;
    char title[length];
    char createdDate[length];
    int completed;
} Todo;

Todo todolist[100] = {0}; // This initialization is important
还有一系列的待办事项

Todo todolist[100];
和要素:

Todo newTodo = {...}

将元素添加到数组的最佳方式是什么?

对于常规数组,只需执行以下操作:

todolist[index] = newTodo;
但是,如果您需要它,最好添加一个字段来指示单元格是否已初始化,这样您就可以知道它是否包含有价值的信息。你可以这样做:

typedef struct
{
    char title[length];
    char createdDate[length];
    int completed;
} Todo;

typedef struct
{
    int initialized;
    char title[length];
    char createdDate[length];
    int completed;
} Todo;

Todo todolist[100] = {0}; // This initialization is important
现在我们可以用这样的方法将第一个空闲单元分配给一个新的
Todo

size_t i=0;

while( !todolist[i].initialized ) {
    i++;

    if( i >= 100 ) {
    /* Handle error */
    }
}

todolist[i] = newTodo;

不能像这样向数组中添加元素。你可以1。跟踪实际使用的元素数量,并在添加元素时添加数量。2.动态分配数组并使用
realloc()
添加元素(在这种情况下,您还必须自己跟踪元素的数量)
todolist[index]=newTodo
您应该在
while
的条件下进行范围检查,以避免超出范围的访问。@MikeCAT Oh boy。我觉得自己愚蠢吗D