Iterate through a C array

后端 未结 4 1351
南笙
南笙 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: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.

提交回复
热议问题