1

Suppose we have a structure array of up to 50 elements that will be added in turn from a buffer write function. How do I find the current number of recordings made in array if the maximum number of items has not been reached?

typedef struct
{
    remoteInstructionReceived_t instruction;
    uint16_t parameter;
} instructionData_type;

remoteInstructionReceived_t commandBuffer[50];
P47 R1ck
  • 148
  • 1
  • 12
  • Use a variable to keep track of it? –  May 02 '18 at 08:17
  • @FelixPalmen That's how I do, already. Is the most reasonable solution. – P47 R1ck May 02 '18 at 22:41
  • Its easy! Please see my answer [here.](https://stackoverflow.com/questions/9170643/find-the-no-of-elements-in-an-array-of-structs/76100693#76100693) – Zeni Apr 25 '23 at 11:41

3 Answers3

1

C arrays are fixed-size: there are always exactly 50 objects in your array. If your program logic requires some of them to be "inactive" (e.g. not written yet), you must keep track of such information separately. For example, you could use a size_t variable to store the number of "valid" entries in the array.

An alternative would be to designate a value of remoteInstructionReceived_t as a terminator, similarly to how 0 is used as a terminator for NUL-terminated strings. Then, you wouldn't have to track the "useful length" of the array separately, but you'd have to ensure a terminator always follows the last valid item in it.

In general, length-tracking is likely both more efficient and more maintainable. I am only mentioning the second (terminator) option out of a sense of completeness.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • So for array structures I can not use any strlen() like function? – P47 R1ck May 02 '18 at 08:27
  • @P47R1ck `strlen` works on a NUL-terminated string. That is a buffer of characters whose last element is `0`. If you have a `char x[10]` with random content, `strlen` will not work on it either. If you introduce a similar convention for your array (such as the terminator having `parameter == 0` or `parameter == ~0u`), you can build a function equivalent to `strlen`. I will add this to the answer. – Angew is no longer proud of SO May 02 '18 at 08:35
0

You can't, C doesn't have a way of knowing if a variable "has a value". All values are values, and no value is more real than any else.

The answer is that additional state, i.e. some form of counter variable, is required to hold this information. Typically you use that when inserting new records, to know where the next record should go.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

Have you considered using a different data structure? You can wrap your structure to allow the creation of a linked list, for example. The deletion would be real just by freeing memory. Besides, it's more efficient for some kinds of operation, such as addin elements in the middle of the list.

Bruno Silva
  • 548
  • 3
  • 6