How do I find the length of an array?

前端 未结 27 2919
轮回少年
轮回少年 2020-11-21 23:10

Is there a way to find how many values an array has? Detecting whether or not I\'ve reached the end of an array would also work.

27条回答
  •  别那么骄傲
    2020-11-21 23:22

    ANSWER:

    int number_of_elements = sizeof(array)/sizeof(array[0])
    

    EXPLANATION:

    Since the compiler sets a specific size chunk of memory aside for each type of data, and an array is simply a group of those, you simply divide the size of the array by the size of the data type. If I have an array of 30 strings, my system sets aside 24 bytes for each element(string) of the array. At 30 elements, that's a total of 720 bytes. 720/24 == 30 elements. The small, tight algorithm for that is:

    int number_of_elements = sizeof(array)/sizeof(array[0]) which equates to

    number_of_elements = 720/24

    Note that you don't need to know what data type the array is, even if it's a custom data type.

提交回复
热议问题