How do I determine the size of my array in C?
That is, the number of elements the array can hold?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Executive summary:
Full answer:
To determine the size of your array in bytes, you can use the
sizeofoperator:On my computer, ints are 4 bytes long, so n is 68.
To determine the number of elements in the array, we can divide the total size of the array by the size of the array element. You could do this with the type, like this:
and get the proper answer (68 / 4 = 17), but if the type of
achanged you would have a nasty bug if you forgot to change thesizeof(int)as well.So the preferred divisor is
sizeof(a[0])or the equivalentsizeof(*a), the size of the first element of the array.Another advantage is that you can now easily parameterize the array name in a macro and get: