Iterate through a C array

后端 未结 4 1324
南笙
南笙 2020-12-02 22:41

I have an array of structs that I created somewhere in my program.

Later, I want to iterate through that, but I don\'t have the size of the array.

How can I

相关标签:
4条回答
  • 2020-12-02 23:00

    I think you should store the size somewhere.

    The null-terminated-string kind of model for determining array length is a bad idea. For instance, getting the size of the array will be O(N) when it could very easily have been O(1) otherwise.

    Having that said, a good solution might be glib's Arrays, they have the added advantage of expanding automatically if you need to add more items.

    P.S. to be completely honest, I haven't used much of glib, but I think it's a (very) reputable library.

    0 讨论(0)
  • 2020-12-02 23:12

    You can store the size somewhere, or you can have a struct with a special value set that you use as a sentinel, the same way that '\0' indicates the end of a string.

    0 讨论(0)
  • 2020-12-02 23:20

    If the size of the array is known at compile time, you can use the structure size to determine the number of elements.

    struct foo fooarr[10];
    
    for(i = 0; i < sizeof(fooarr) / sizeof(struct foo); i++)
    {
      do_something(fooarr[i].data);
    }
    

    If it is not known at compile time, you will need to store a size somewhere or create a special terminator value at the end of the array.

    0 讨论(0)
  • 2020-12-02 23:24

    It depends. If it's a dynamically allocated array, that is, you created it calling malloc, then as others suggest you must either save the size of the array/number of elements somewhere or have a sentinel (a struct with a special value, that will be the last one).

    If it's a static array, you can sizeof it's size/the size of one element. For example:

    int array[10], array_size;
    ...
    array_size = sizeof(array)/sizeof(int);
    

    Note that, unless it's global, this only works in the scope where you initialized the array, because if you past it to another function it gets decayed to a pointer.

    Hope it helps.

    0 讨论(0)
提交回复
热议问题