1

I have a struct like this:

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

and an array of these todos

Todo todolist[100];

and the element:

Todo newTodo = {...}

What's the best way to the element to the array?

2
  • 3
    You cannot add elements to arrays like this. You can 1. Keep track the number of actually used elements and add the number when adding elements. 2. Allocate arrays dynamically and use realloc() to add elements (You will also have to keep track the number of elements by yourself in this case) Commented Mar 27, 2021 at 22:47
  • todolist[index] = newTodo Commented Mar 27, 2021 at 23:05

1 Answer 1

1

For a regular array, just do this:

todolist[index] = newTodo;

However, if you need it, it can be wise to add a field to indicate if the cell is initialized or not, so you know if it contains valuable info. You could do like this:

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

Todo todolist[100] = {0}; // This initialization is important

And now we can du stuff like this to assign first free cell to a new Todo:

size_t i=0;

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

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

todolist[i] = newTodo;
Sign up to request clarification or add additional context in comments.

1 Comment

You should do the range check inside the condition of while to avoid out-of-range access.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.