iterating in a array in C

前端 未结 4 1826
南笙
南笙 2020-12-11 12:06

Hey I have something of this type

eph_t *a;

The type is eph_t as you can see. Its an array in C but I do not know the size of the array nor

4条回答
  •  醉话见心
    2020-12-11 13:01

    As others have said, it is unsafe to iterate over an array when you do not know the end of the array. This is often worked around in the following way.

    1. If you have access to the array declaration (int a[10];) for example. you can use the sizeof operator to determine the array's size. Please note this WILL NOT WORK when passing a pointer to an array to a function.
    2. Functions that use an array will often take a direct size or some way to infer the size as extra parameters to the function (memset is a good example)
    3. The array may have a special terminator element (usually a NULL or 0 element at the end) when means you may not iterate beyond (C strings are good examples)

    So if you are designing a function that takes an array as a parameter, please use the above patterns. If you are using a function that does not use one of the above pattern, report the problem to the library designer as a bug.

提交回复
热议问题