<p>How do I determine the size of my array in C? </p>

<p>That is, the number of elements the array can hold?</p>

[{'answer_id': 37539, 'author': 'Mark Harrison', 'author_id': 116, 'author_profile': 'https://Stackoverflow.com/users/116', 'pm_score': 12, 'selected': True, 'text': '<p><strong>Executive summary:</strong></p>\n\n<pre><code>int a[17];\nsize_t n = sizeof(a)/sizeof(a[0]);\n</code></pre>\n\n<hr>\n\n<p><strong>Full answer:</strong></p>\n\n<p>To determine the size of your array in bytes, you can use the <code>sizeof</code>\noperator:</p>\n\n<pre><code>int a[17];\nsize_t n = sizeof(a);\n</code></pre>\n\n<p>On my computer, ints are 4 bytes long, so n is 68.</p>\n\n<p>To determine the number of elements in the array, we can divide\nthe total size of the array by the size of the array element.\nYou could do this with the type, like this:</p>\n\n<pre><code>int a[17];\nsize_t n = sizeof(a) / sizeof(int);\n</code></pre>\n\n<p>and get the proper answer (68 / 4 = 17), but if the type of\n<code>a</code> changed you would have a nasty bug if you forgot to change\nthe <code>sizeof(int)</code> as well.</p>\n\n<p>So the preferred divisor is <code>sizeof(a[0])</code> or the equivalent <code>sizeof(*a)</code>, the size of the first element of the array.</p>\n\n<pre><code>int a[17];\nsize_t n = sizeof(a) / sizeof(a[0]);\n</code></pre>\n\n<p>Another advantage is that you can now easily parameterize\nthe array name in a macro and get:</p>\n\n<pre><code>#define NELEMS(x)  (sizeof(x) / sizeof((x)[0]))\n\nint a[17];\nsize_t n = NELEMS(a);\n</code></pre>\n'}, {'answer_id': 37541, 'author': 'T Percival', 'author_id': 954, 'author_profile': 'https://Stackoverflow.com/users/954', 'pm_score': 4, 'selected': False, 'text': '<pre><code>sizeof(array) / sizeof(array[0])\n</code></pre>\n'}, {'answer_id': 37545, 'author': 'Magnus Hoff', 'author_id': 2971, 'author_profile': 'https://Stackoverflow.com/users/2971', 'pm_score': 7, 'selected': False, 'text': '<p>It is worth noting that <code>sizeof</code> doesn\'t help when dealing with an array value that has decayed to a pointer: even though it points to the start of an array, to the compiler it is the same as a pointer to a single element of that array. A pointer does not "remember" anything else about the array that was used to initialize it.</p>\n\n<pre><code>int a[10];\nint* p = a;\n\nassert(sizeof(a) / sizeof(a[0]) == 10);\nassert(sizeof(p) == sizeof(int*));\nassert(sizeof(*p) == sizeof(int));\n</code></pre>\n'}, {'answer_id': 204232, 'author': 'unwind', 'author_id': 28169, 'author_profile': 'https://Stackoverflow.com/users/28169', 'pm_score': 6, 'selected': False, 'text': "<p>The <code>sizeof</code> &quot;trick&quot; is the best way I know, with one small but (to me, this being a major pet peeve) important change in the use of parenthesis.</p>\n<p>As the Wikipedia entry makes clear, C's <code>sizeof</code> is not a function; it's an <strong>operator</strong>. Thus, it does not require parenthesis around its argument, unless the argument is a type name. This is easy to remember, since it makes the argument look like a cast expression, which also uses parenthesis.</p>\n<p>So: If you have the following:</p>\n<pre><code>int myArray[10];\n</code></pre>\n<p>You can find the number of elements with code like this:</p>\n<pre><code>size_t n = sizeof myArray / sizeof *myArray;\n</code></pre>\n<p>That, to me, reads a lot easier than the alternative with parenthesis. I also favor use of the asterisk in the right-hand part of the division, since it's more concise than indexing.</p>\n<p>Of course, this is all compile-time too, so there's no need to worry about the division affecting the performance of the program. So use this form wherever you can.</p>\n<p>It is always best to use <code>sizeof</code> on an actual object when you have one, rather than on a type, since then you don't need to worry about making an error and stating the wrong type.</p>\n<p>For instance, say you have a function that outputs some data as a stream of bytes, for instance across a network. Let's call the function <code>send()</code>, and make it take as arguments a pointer to the object to send, and the number of bytes in the object. So, the prototype becomes:</p>\n<pre><code>void send(const void *object, size_t size);\n</code></pre>\n<p>And then you need to send an integer, so you code it up like this:</p>\n<pre><code>int foo = 4711;\nsend(&amp;foo, sizeof (int));\n</code></pre>\n<p>Now, you've introduced a subtle way of shooting yourself in the foot, by specifying the type of <code>foo</code> in two places. If one changes but the other doesn't, the code breaks. Thus, always do it like this:</p>\n<pre><code>send(&amp;foo, sizeof foo);\n</code></pre>\n<p>Now you're protected. Sure, you duplicate the name of the variable, but that has a high probability of breaking in a way the compiler can detect, if you change it.</p>\n"}, {'answer_id': 7093560, 'author': 'Andreas Spindler', 'author_id': 887771, 'author_profile': 'https://Stackoverflow.com/users/887771', 'pm_score': 4, 'selected': False, 'text': '<p>For <strong>multidimensional arrays</strong> it is a tad more complicated. Oftenly people define explicit macro constants, i.e. </p>\n\n<pre><code>#define g_rgDialogRows   2\n#define g_rgDialogCols   7\n\nstatic char const* g_rgDialog[g_rgDialogRows][g_rgDialogCols] =\n{\n    { " ",  " ",    " ",    " 494", " 210", " Generic Sample Dialog", " " },\n    { " 1", " 330", " 174", " 88",  " ",    " OK",        " " },\n};\n</code></pre>\n\n<p>But these constants can be evaluated at compile-time too with <em>sizeof</em>:</p>\n\n<pre><code>#define rows_of_array(name)       \\\n    (sizeof(name   ) / sizeof(name[0][0]) / columns_of_array(name))\n#define columns_of_array(name)    \\\n    (sizeof(name[0]) / sizeof(name[0][0]))\n\nstatic char* g_rgDialog[][7] = { /* ... */ };\n\nassert(   rows_of_array(g_rgDialog) == 2);\nassert(columns_of_array(g_rgDialog) == 7);\n</code></pre>\n\n<p>Note that this code works in C and C++. For arrays with more than two dimensions use</p>\n\n<pre><code>sizeof(name[0][0][0])\nsizeof(name[0][0][0][0])\n</code></pre>\n\n<p>etc., ad infinitum.</p>\n'}, {'answer_id': 8129291, 'author': 'Ohad', 'author_id': 1046490, 'author_profile': 'https://Stackoverflow.com/users/1046490', 'pm_score': 0, 'selected': False, 'text': '<p>&quot;you\'ve introduced a subtle way of shooting yourself in the foot&quot;</p>\n<p>C \'native\' arrays do not store their size. It is therefore recommended to save the length of the array in a separate variable/const, and pass it whenever you pass the array, that is:</p>\n<pre><code>#define MY_ARRAY_LENGTH   15\nint myArray[MY_ARRAY_LENGTH];\n</code></pre>\n<p><strong>If you are writing C++</strong>, you SHOULD always avoid native arrays anyway (unless you can\'t, in which case, mind your foot). If you are writing C++, use the <a href="http://en.wikipedia.org/wiki/Standard_Template_Library" rel="nofollow noreferrer">STL</a>\'s \'vector\' container. &quot;Compared to arrays, they provide almost the same performance&quot;, and they are far more useful!</p>\n<pre><code>// vector is a template, the &lt;int&gt; means it is a vector of ints\nvector&lt;int&gt; numbers;  \n\n// push_back() puts a new value at the end (or back) of the vector\nfor (int i = 0; i &lt; 10; i++)\n    numbers.push_back(i);\n\n// Determine the size of the array\ncout &lt;&lt; numbers.size();\n</code></pre>\n<p>See:\n<a href="http://www.cplusplus.com/reference/stl/vector/" rel="nofollow noreferrer">http://www.cplusplus.com/reference/stl/vector/</a></p>\n'}, {'answer_id': 10349610, 'author': 'Elideb', 'author_id': 481534, 'author_profile': 'https://Stackoverflow.com/users/481534', 'pm_score': 10, 'selected': False, 'text': '<p>The <code>sizeof</code> way is the right way <a href="https://en.wikipedia.org/wiki/If_and_only_if" rel="noreferrer"><em>iff</em></a> you are dealing with arrays not received as parameters. An array sent as a parameter to a function is treated as a pointer, so <code>sizeof</code> will return the pointer\'s size, instead of the array\'s.</p>\n\n<p>Thus, inside functions this method does not work. Instead, always pass an additional parameter <code>size_t size</code> indicating the number of elements in the array.</p>\n\n<p>Test:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nvoid printSizeOf(int intArray[]);\nvoid printLength(int intArray[]);\n\nint main(int argc, char* argv[])\n{\n    int array[] = { 0, 1, 2, 3, 4, 5, 6 };\n\n    printf("sizeof of array: %d\\n", (int) sizeof(array));\n    printSizeOf(array);\n\n    printf("Length of array: %d\\n", (int)( sizeof(array) / sizeof(array[0]) ));\n    printLength(array);\n}\n\nvoid printSizeOf(int intArray[])\n{\n    printf("sizeof of parameter: %d\\n", (int) sizeof(intArray));\n}\n\nvoid printLength(int intArray[])\n{\n    printf("Length of parameter: %d\\n", (int)( sizeof(intArray) / sizeof(intArray[0]) ));\n}\n</code></pre>\n\n<p>Output (in a 64-bit Linux OS):</p>\n\n<pre><code>sizeof of array: 28\nsizeof of parameter: 8\nLength of array: 7\nLength of parameter: 2\n</code></pre>\n\n<p>Output (in a 32-bit windows OS):</p>\n\n<pre><code>sizeof of array: 28\nsizeof of parameter: 4\nLength of array: 7\nLength of parameter: 1\n</code></pre>\n'}, {'answer_id': 16354807, 'author': 'Shih-En Chou', 'author_id': 924578, 'author_profile': 'https://Stackoverflow.com/users/924578', 'pm_score': 2, 'selected': False, 'text': '<p>You can use the <code>&amp;</code> operator. Here is the source code:</p>\n\n<pre><code>#include&lt;stdio.h&gt;\n#include&lt;stdlib.h&gt;\nint main(){\n\n    int a[10];\n\n    int *p; \n\n    printf("%p\\n", (void *)a); \n    printf("%p\\n", (void *)(&amp;a+1));\n    printf("---- diff----\\n");\n    printf("%zu\\n", sizeof(a[0]));\n    printf("The size of array a is %zu\\n", ((char *)(&amp;a+1)-(char *)a)/(sizeof(a[0])));\n\n\n    return 0;\n};\n</code></pre>\n\n<p>Here is the sample output</p>\n\n<pre><code>1549216672\n1549216712\n---- diff----\n4\nThe size of array a is 10\n</code></pre>\n'}, {'answer_id': 17089267, 'author': 'Joel Dentici', 'author_id': 2482551, 'author_profile': 'https://Stackoverflow.com/users/2482551', 'pm_score': 3, 'selected': False, 'text': '<p>If you really want to do this to pass around your array I suggest implementing a structure to store a pointer to the type you want an array of and an integer representing the size of the array. Then you can pass that around to your functions. Just assign the array variable value (pointer to first element) to that pointer. Then you can go <code>Array.arr[i]</code> to get the i-th element and use <code>Array.size</code> to get the number of elements in the array.</p>\n\n<p>I included some code for you. It\'s not very useful but you could extend it with more features. To be honest though, if these are the things you want you should stop using C and use another language with these features built in.</p>\n\n<pre><code>/* Absolutely no one should use this...\n   By the time you\'re done implementing it you\'ll wish you just passed around\n   an array and size to your functions */\n/* This is a static implementation. You can get a dynamic implementation and \n   cut out the array in main by using the stdlib memory allocation methods,\n   but it will work much slower since it will store your array on the heap */\n\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n/*\n#include "MyTypeArray.h"\n*/\n/* MyTypeArray.h \n#ifndef MYTYPE_ARRAY\n#define MYTYPE_ARRAY\n*/\ntypedef struct MyType\n{\n   int age;\n   char name[20];\n} MyType;\ntypedef struct MyTypeArray\n{\n   int size;\n   MyType *arr;\n} MyTypeArray;\n\nMyType new_MyType(int age, char *name);\nMyTypeArray newMyTypeArray(int size, MyType *first);\n/*\n#endif\nEnd MyTypeArray.h */\n\n/* MyTypeArray.c */\nMyType new_MyType(int age, char *name)\n{\n   MyType d;\n   d.age = age;\n   strcpy(d.name, name);\n   return d;\n}\n\nMyTypeArray new_MyTypeArray(int size, MyType *first)\n{\n   MyTypeArray d;\n   d.size = size;\n   d.arr = first;\n   return d;\n}\n/* End MyTypeArray.c */\n\n\nvoid print_MyType_names(MyTypeArray d)\n{\n   int i;\n   for (i = 0; i &lt; d.size; i++)\n   {\n      printf("Name: %s, Age: %d\\n", d.arr[i].name, d.arr[i].age);\n   }\n}\n\nint main()\n{\n   /* First create an array on the stack to store our elements in.\n      Note we could create an empty array with a size instead and\n      set the elements later. */\n   MyType arr[] = {new_MyType(10, "Sam"), new_MyType(3, "Baxter")};\n   /* Now create a "MyTypeArray" which will use the array we just\n      created internally. Really it will just store the value of the pointer\n      "arr". Here we are manually setting the size. You can use the sizeof\n      trick here instead if you\'re sure it will work with your compiler. */\n   MyTypeArray array = new_MyTypeArray(2, arr);\n   /* MyTypeArray array = new_MyTypeArray(sizeof(arr)/sizeof(arr[0]), arr); */\n   print_MyType_names(array);\n   return 0;\n}\n</code></pre>\n'}, {'answer_id': 20447621, 'author': 'Arjun Sreedharan', 'author_id': 997813, 'author_profile': 'https://Stackoverflow.com/users/997813', 'pm_score': 5, 'selected': False, 'text': '<pre><code>int size = (&amp;arr)[1] - arr;\n</code></pre>\n\n<p>Check out <a href="http://arjunsreedharan.org/post/69303442896/the-difference-between-arr-and-arr-how-to-find-size" rel="noreferrer" title="this link">this link</a> for explanation</p>\n'}, {'answer_id': 21208828, 'author': 'Abhitesh khatri', 'author_id': 1863721, 'author_profile': 'https://Stackoverflow.com/users/1863721', 'pm_score': 5, 'selected': False, 'text': "<p>If you know the data type of the array, you can use something like:</p>\n\n<pre><code>int arr[] = {23, 12, 423, 43, 21, 43, 65, 76, 22};\n\nint noofele = sizeof(arr)/sizeof(int);\n</code></pre>\n\n<p>Or if you don't know the data type of array, you can use something like:</p>\n\n<pre><code>noofele = sizeof(arr)/sizeof(arr[0]);\n</code></pre>\n\n<p>Note: This thing only works if the array is not defined at run time (like malloc) and the array is not passed in a function. In both cases, <code>arr</code> (array name) is a pointer.</p>\n"}, {'answer_id': 22084606, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>The macro <code>ARRAYELEMENTCOUNT(x)</code> that everyone is making use of evaluates <strong>incorrectly</strong>. This, realistically, is just a sensitive matter, because you can\'t have expressions that result in an \'array\' type.</p>\n\n<pre><code>/* Compile as: CL /P "macro.c" */\n# define ARRAYELEMENTCOUNT(x) (sizeof (x) / sizeof (x[0]))\n\nARRAYELEMENTCOUNT(p + 1);\n</code></pre>\n\n<p><em>Actually</em> evaluates as:</p>\n\n<pre><code>(sizeof (p + 1) / sizeof (p + 1[0]));\n</code></pre>\n\n<p>Whereas</p>\n\n<pre><code>/* Compile as: CL /P "macro.c" */\n# define ARRAYELEMENTCOUNT(x) (sizeof (x) / sizeof (x)[0])\n\nARRAYELEMENTCOUNT(p + 1);\n</code></pre>\n\n<p>It correctly evaluates to:</p>\n\n<pre><code>(sizeof (p + 1) / sizeof (p + 1)[0]);\n</code></pre>\n\n<p>This really doesn\'t have a lot to do with the size of arrays explicitly. I\'ve just noticed a lot of errors from not truly observing how the C preprocessor works. You always wrap the macro parameter, not an expression in might be involved in.</p>\n\n<hr>\n\n<p>This is correct; my example was a bad one. But that\'s actually exactly what should happen. As I previously mentioned <code>p + 1</code> will end up as a pointer type and invalidate the entire macro (just like if you attempted to use the macro in a function with a pointer parameter).</p>\n\n<p>At the end of the day, in this <em>particular</em> instance, the fault doesn\'t really matter (so I\'m just wasting everyone\'s time; huzzah!), because you don\'t have expressions with a type of \'array\'. But really the point about preprocessor evaluation subtles I think is an important one.</p>\n'}, {'answer_id': 33820627, 'author': 'Yogeesh H T', 'author_id': 3725702, 'author_profile': 'https://Stackoverflow.com/users/3725702', 'pm_score': 4, 'selected': False, 'text': '<p>Size of an array in C:</p>\n\n<pre><code>int a[10];\nsize_t size_of_array = sizeof(a);      // Size of array a\nint n = sizeof (a) / sizeof (a[0]);    // Number of elements in array a\nsize_t size_of_element = sizeof(a[0]); // Size of each element in array a                                          \n                                       // Size of each element = size of type\n</code></pre>\n'}, {'answer_id': 35459621, 'author': 'Paulo Pinheiro', 'author_id': 5343389, 'author_profile': 'https://Stackoverflow.com/users/5343389', 'pm_score': 3, 'selected': False, 'text': '<p>The best way is you save this information, for example, in a structure:</p>\n\n<pre><code>typedef struct {\n     int *array;\n     int elements;\n} list_s;\n</code></pre>\n\n<p>Implement all necessary functions such as create, destroy, check equality, and everything else you need. It is easier to pass as a parameter.</p>\n'}, {'answer_id': 39453211, 'author': 'Andy Nugent', 'author_id': 2964597, 'author_profile': 'https://Stackoverflow.com/users/2964597', 'pm_score': 4, 'selected': False, 'text': '<pre><code>#define SIZE_OF_ARRAY(_array) (sizeof(_array) / sizeof(_array[0]))\n</code></pre>\n'}, {'answer_id': 44217128, 'author': 'Mohd Shibli', 'author_id': 5947210, 'author_profile': 'https://Stackoverflow.com/users/5947210', 'pm_score': 5, 'selected': False, 'text': '<p>You can use the <em>sizeof</em> operator, but it will not work for functions, because it will take the reference of a pointer.\nYou can do the following to find the length of an array:</p>\n<pre><code>len = sizeof(arr)/sizeof(arr[0])\n</code></pre>\n<p>The code was originally found here:</p>\n<p><a href="http://www.psychocodes.in/c-program-to-find-the-number-of-elements-in-an-array-length-of-an-array-in-c.html" rel="nofollow noreferrer">C program to find the number of elements in an array</a></p>\n'}, {'answer_id': 51392277, 'author': 'Pygirl', 'author_id': 6660373, 'author_profile': 'https://Stackoverflow.com/users/6660373', 'pm_score': -1, 'selected': False, 'text': '<p><strong>Note:</strong> This one can give you undefined behaviour as <a href="https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c/37539#comment91048046_51392277">pointed out by M.M</a> in the comment.</p>\n<pre><code>int a[10];\nint size = (*(&amp;a+1)-a);\n</code></pre>\n<p>For more details, see <a href="https://aticleworld.com/how-to-find-sizeof-array-in-cc-without-using-sizeof/" rel="nofollow noreferrer">here</a> and also <a href="https://www.geeksforgeeks.org/how-to-find-size-of-array-in-cc-without-using-sizeof-operator/" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 51927643, 'author': 'Keivan', 'author_id': 4623372, 'author_profile': 'https://Stackoverflow.com/users/4623372', 'pm_score': 3, 'selected': False, 'text': "<p>The function <code>sizeof</code> returns the number of bytes which is used by your array in the memory. If you want to calculate the number of elements in your array, you should divide that number with the <code>sizeof</code> variable type of the array. Let's say <code>int array[10];</code>, if variable type integer in your computer is 32 bit (or 4 bytes), in order to get the size of your array, you should do the following:</p>\n<pre><code>int array[10];\nsize_t sizeOfArray = sizeof(array)/sizeof(int);\n</code></pre>\n"}, {'answer_id': 57408735, 'author': 'Jency', 'author_id': 9384858, 'author_profile': 'https://Stackoverflow.com/users/9384858', 'pm_score': 1, 'selected': False, 'text': '<p>The simplest answer:</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(void) {\n\n    int a[] = {2,3,4,5,4,5,6,78,9,91,435,4,5,76,7,34}; // For example only\n    int size;\n\n    size = sizeof(a)/sizeof(a[0]); // Method\n\n    printf(&quot;size = %d&quot;, size);\n    return 0;\n}\n</code></pre>\n'}, {'answer_id': 57537491, 'author': 'alx', 'author_id': 6872717, 'author_profile': 'https://Stackoverflow.com/users/6872717', 'pm_score': 5, 'selected': False, 'text': '<p><strong>I would advise to never use <code>sizeof</code> (even if it can be used) to get any of the two different sizes of an array, either in number of elements or in bytes, which are the last two cases I show here.  For each of the two sizes, the macros shown below can be used to make it safer.  The reason is to make obvious the intention of the code to maintainers, and difference <code>sizeof(ptr)</code> from <code>sizeof(arr)</code> at first glance (which written this way isn\'t obvious), so that bugs are then obvious for everyone reading the code.</strong></p>\n<hr />\n<p><strong>TL;DR:</strong></p>\n<pre class="lang-c prettyprint-override"><code>#define ARRAY_SIZE(arr)   (sizeof(arr) / sizeof((arr)[0]) + must_be_array(arr))\n#define ARRAY_BYTES(arr)  (sizeof(arr) + must_be_array(arr))\n</code></pre>\n<p><code>must_be_array(arr)</code> (defined below) IS needed as <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94746" rel="nofollow noreferrer"><code>-Wsizeof-pointer-div</code> is buggy</a> (as of april/2020):</p>\n<pre class="lang-c prettyprint-override"><code>#define is_same_type(a, b)  __builtin_types_compatible_p(typeof(a), typeof(b))\n#define is_array(arr)       (!is_same_type((arr), &amp;(arr)[0]))\n#define must_be(e)                                                      \\\n(                                                                       \\\n        0 * (int)sizeof(                                                \\\n                struct {                                                \\\n                        static_assert(e);                               \\\n                        char ISO_C_forbids_a_struct_with_no_members__;  \\\n                }                                                       \\\n        )                                                               \\\n)\n#define must_be_array(arr)  must_be(is_array(arr))\n</code></pre>\n<hr />\n<p>There have been important bugs regarding this topic: <a href="https://lkml.org/lkml/2015/9/3/428" rel="nofollow noreferrer">https://lkml.org/lkml/2015/9/3/428</a></p>\n<p>I disagree with the solution that Linus provides, which is to never use array notation for parameters of functions.</p>\n<p>I like array notation as documentation that a pointer is being used as an array.  But that means that a fool-proof solution needs to be applied so that it is impossible to write buggy code.</p>\n<p>From an array we have three sizes which we might want to know:</p>\n<ul>\n<li>The size of the elements of the array</li>\n<li>The number of elements in the array</li>\n<li>The size in bytes that the array uses in memory</li>\n</ul>\n<hr />\n<h2>The size of the elements of the array</h2>\n<p>The first one is very simple, and it doesn\'t matter if we are dealing with an array or a pointer, because it\'s done the same way.</p>\n<p>Example of usage:</p>\n<pre class="lang-c prettyprint-override"><code>void foo(size_t nmemb, int arr[nmemb])\n{\n        qsort(arr, nmemb, sizeof(arr[0]), cmp);\n}\n</code></pre>\n<p><code>qsort()</code> needs this value as its third argument.</p>\n<hr />\n<p>For the other two sizes, which are the topic of the question, we want to make sure that we\'re dealing with an array, and break the compilation if not, because if we\'re dealing with a pointer, we will get wrong values.  When the compilation is broken, we will be able to easily see that we weren\'t dealing with an array, but with a pointer instead, and we will just have to write the code with a variable or a macro that stores the size of the array behind the pointer.</p>\n<hr />\n<h2>The number of elements in the array</h2>\n<p>This one is the most common, and many answers have provided you with the typical macro <code>ARRAY_SIZE</code>:</p>\n<pre class="lang-c prettyprint-override"><code>#define ARRAY_SIZE(arr)     (sizeof(arr) / sizeof((arr)[0]))\n</code></pre>\n<p>Recent versions of compilers, such as GCC 8, will warn you when you apply this macro to a pointer, so it is safe (there are other methods to make it safe with older compilers).</p>\n<p>It works by dividing the size in bytes of the whole array by the size of each element.</p>\n<p>Examples of usage:</p>\n<pre class="lang-c prettyprint-override"><code>void foo(size_t nmemb)\n{\n        char buf[nmemb];\n\n        fgets(buf, ARRAY_SIZE(buf), stdin);\n}\n\nvoid bar(size_t nmemb)\n{\n        int arr[nmemb];\n\n        for (size_t i = 0; i &lt; ARRAY_SIZE(arr); i++)\n                arr[i] = i;\n}\n</code></pre>\n<p>If these functions didn\'t use arrays, but got them as parameters instead, the former code would not compile, so it would be impossible to have a bug (given that a recent compiler version is used, or that some other trick is used), and we need to replace the macro call by the value:</p>\n<pre class="lang-c prettyprint-override"><code>void foo(size_t nmemb, char buf[nmemb])\n{\n        fgets(buf, nmemb, stdin);\n}\n\nvoid bar(size_t nmemb, int arr[nmemb])\n{\n        for (size_t i = nmemb - 1; i &lt; nmemb; i--)\n                arr[i] = i;\n}\n</code></pre>\n<hr />\n<h2>The size in bytes that the array uses in memory</h2>\n<p><code>ARRAY_SIZE</code> is commonly used as a solution to the previous case, but this case is rarely written safely, maybe because it\'s less common.</p>\n<p>The common way to get this value is to use <code>sizeof(arr)</code>.  The problem: the same as with the previous one; if you have a pointer instead of an array, your program will go nuts.</p>\n<p>The solution to the problem involves using the same macro as before, which we know to be safe (it breaks compilation if it is applied to a pointer):</p>\n<pre class="lang-c prettyprint-override"><code>#define ARRAY_BYTES(arr)        (sizeof((arr)[0]) * ARRAY_SIZE(arr))\n</code></pre>\n<p>How it works is very simple:  it undoes the division that <code>ARRAY_SIZE</code> does, so after mathematical cancellations you end up with just one <code>sizeof(arr)</code>, but with the added safety of the <code>ARRAY_SIZE</code> construction.</p>\n<p>Example of usage:</p>\n<pre class="lang-c prettyprint-override"><code>void foo(size_t nmemb)\n{\n        int arr[nmemb];\n\n        memset(arr, 0, ARRAY_BYTES(arr));\n}\n</code></pre>\n<p><code>memset()</code> needs this value as its third argument.</p>\n<p>As before, if the array is received as a parameter (a pointer), it won\'t compile, and we will have to replace the macro call by the value:</p>\n<pre class="lang-c prettyprint-override"><code>void foo(size_t nmemb, int arr[nmemb])\n{\n        memset(arr, 0, sizeof(arr[0]) * nmemb);\n}\n</code></pre>\n<hr />\n<h3>Update (23/apr/2020): <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94746" rel="nofollow noreferrer"><code>-Wsizeof-pointer-div</code> is buggy</a>:</h3>\n<p>Today I found out that the new warning in GCC only works if the macro is defined in a header that is not a system header.  If you define the macro in a header that is installed in your system (usually <code>/usr/local/include/</code> or <code>/usr/include/</code>) (<code>#include &lt;foo.h&gt;</code>), the compiler will NOT emit a warning (I tried GCC 9.3.0).</p>\n<p>So we have <code>#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))</code> and want to make it safe.  We will need C2X <code>static_assert()</code> and some GCC extensions: <a href="https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html#Statement-Exprs" rel="nofollow noreferrer">Statements and Declarations in Expressions</a>, <a href="https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html" rel="nofollow noreferrer">__builtin_types_compatible_p</a>:</p>\n<pre class="lang-c prettyprint-override"><code>#include &lt;assert.h&gt;\n\n\n#define is_same_type(a, b)      __builtin_types_compatible_p(typeof(a), typeof(b))\n#define is_array(arr)           (!is_same_type((arr), &amp;(arr)[0]))\n#define Static_assert_array(arr) static_assert(is_array(arr))\n\n#define ARRAY_SIZE(arr)                                                 \\\n({                                                                      \\\n        Static_assert_array(arr);                                       \\\n        sizeof(arr) / sizeof((arr)[0]);                                 \\\n})\n</code></pre>\n<p>Now <code>ARRAY_SIZE()</code> is completely safe, and therefore all its derivatives will be safe.</p>\n<hr />\n<h2>Update: libbsd provides <code>__arraycount()</code>:</h2>\n<p><a href="https://libbsd.freedesktop.org" rel="nofollow noreferrer">Libbsd</a> provides the macro <code>__arraycount()</code> in <a href="https://cgit.freedesktop.org/libbsd/tree/include/bsd/sys/cdefs.h" rel="nofollow noreferrer"><code>&lt;sys/cdefs.h&gt;</code></a>, which is unsafe because it lacks a pair of parentheses, but we can add those parentheses ourselves, and therefore we don\'t even need to write the division in our header (why would we duplicate code that already exists?).  That macro is defined in a system header, so if we use it we are forced to use the macros above.</p>\n<pre class="lang-c prettyprint-override"><code>#inlcude &lt;assert.h&gt;\n#include &lt;stddef.h&gt;\n#include &lt;sys/cdefs.h&gt;\n#include &lt;sys/types.h&gt;\n\n\n#define is_same_type(a, b)      __builtin_types_compatible_p(typeof(a), typeof(b))\n#define is_array(arr)           (!is_same_type((arr), &amp;(arr)[0]))\n#define Static_assert_array(arr) static_assert(is_array(arr))\n\n#define ARRAY_SIZE(arr)                                                 \\\n({                                                                      \\\n        Static_assert_array(arr);                                       \\\n        __arraycount((arr));                                            \\\n})\n\n#define ARRAY_BYTES(arr)        (sizeof((arr)[0]) * ARRAY_SIZE(arr))\n</code></pre>\n<p>Some systems provide <code>nitems()</code> in <a href="https://cvsweb.openbsd.org/src/sys/sys/param.h?rev=1.130&amp;content-type=text/x-cvsweb-markup" rel="nofollow noreferrer"><code>&lt;sys/param.h&gt;</code></a> instead, and some systems provide both.  You should check your system, and use the one you have, and maybe use some preprocessor conditionals for portability and support both.</p>\n<hr />\n<h2>Update: Allow the macro to be used at file scope:</h2>\n<p>Unfortunately, the <code>({})</code> gcc extension cannot be used at file scope.\nTo be able to use the macro at file scope, the static assertion must be\ninside <code>sizeof(struct {})</code>.  Then, multiply it by <code>0</code> to not affect\nthe result.  A cast to <code>(int)</code> might be good to simulate a function\nthat returns <code>(int)0</code> (in this case it is not necessary, but then it\nis reusable for other things).</p>\n<p>Additionally, the definition of <code>ARRAY_BYTES()</code> can be simplified a bit.</p>\n<pre class="lang-c prettyprint-override"><code>#include &lt;assert.h&gt;\n#include &lt;stddef.h&gt;\n#include &lt;sys/cdefs.h&gt;\n#include &lt;sys/types.h&gt;\n\n\n#define is_same_type(a, b)     __builtin_types_compatible_p(typeof(a), typeof(b))\n#define is_array(arr)          (!is_same_type((arr), &amp;(arr)[0]))\n#define must_be(e)                                                      \\\n(                                                                       \\\n        0 * (int)sizeof(                                                \\\n                struct {                                                \\\n                        static_assert(e);                               \\\n                        char ISO_C_forbids_a_struct_with_no_members__;  \\\n                }                                                       \\\n        )                                                               \\\n)\n#define must_be_array(arr)      must_be(is_array(arr))\n\n#define ARRAY_SIZE(arr)         (__arraycount((arr)) + must_be_array(arr))\n#define ARRAY_BYTES(arr)        (sizeof(arr) + must_be_array(arr))\n</code></pre>\n<hr />\n<h1>Notes:</h1>\n<p>This code makes use of the following extensions, which are completely necessary, and their presence is absolutely necessary to achieve safety.  If your compiler doesn\'t have them, or some similar ones, then you can\'t achieve this level of safety.</p>\n<ul>\n<li><a href="https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html" rel="nofollow noreferrer"><code>__builtin_types_compatible_p()</code></a></li>\n<li><a href="https://gcc.gnu.org/onlinedocs/gcc/Typeof.html" rel="nofollow noreferrer"><code>typeof()</code></a></li>\n</ul>\n<p>I also make use of the following C2X feature.  However, its absence by using an older standard can be overcome using some dirty tricks (see for example: <a href="https://stackoverflow.com/q/9229601/6872717">What is “:-!!” in C code?</a>) (in C11 you also have <code>static_assert()</code>, but it requires a message).</p>\n<ul>\n<li><a href="https://en.cppreference.com/w/c/language/static_assert" rel="nofollow noreferrer"><code>static_assert()</code></a></li>\n</ul>\n'}, {'answer_id': 59946948, 'author': 'Azatik1000', 'author_id': 5533889, 'author_profile': 'https://Stackoverflow.com/users/5533889', 'pm_score': 2, 'selected': False, 'text': '<p>A more elegant solution will be</p>\n\n<pre><code>size_t size = sizeof(a) / sizeof(*a);\n</code></pre>\n'}, {'answer_id': 60565087, 'author': 'RobertS supports Monica Cellio', 'author_id': 12139179, 'author_profile': 'https://Stackoverflow.com/users/12139179', 'pm_score': -1, 'selected': False, 'text': '<p>Beside the answers already provided, I want to point out a special case by the use of </p>\n\n<pre><code>sizeof(a) / sizeof (a[0])\n</code></pre>\n\n<hr>\n\n<p>If <code>a</code> is either an array of <code>char</code>, <code>unsigned char</code> or <code>signed char</code> you do not need to use <code>sizeof</code> twice since a <code>sizeof</code> expression with one operand of these types do always result to <code>1</code>.</p>\n\n<p>Quote from C18,6.5.3.4/4:  </p>\n\n<blockquote>\n  <p>"<em>When <code>sizeof</code> is applied to an operand that has type <code>char</code>, <code>unsigned char</code>, or <code>signed char</code>, (or a qualified version thereof) the result is <code>1</code>."</em></p>\n</blockquote>\n\n<p>Thus, <code>sizeof(a) / sizeof (a[0])</code> would be equivalent to <code>NUMBER OF ARRAY ELEMENTS / 1</code> if <code>a</code> is an array of type <code>char</code>, <code>unsigned char</code> or <code>signed char</code>. The division through 1 is redundant.</p>\n\n<p>In this case, you can simply abbreviate and do:</p>\n\n<pre><code>sizeof(a)\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>char a[10];\nsize_t length = sizeof(a);\n</code></pre>\n\n<p>If you want a proof, here is a link to <a href="https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qgA%2BhOSkAzpnbICeOpUy10AYVSsArgFtaIAEylV6ADJ5amAHJ6ARpmIgAnKQAOqaYSW1NO/Ubunt50Fla2ug5OrrLyinQMBMzEBH56BsaxmAo%2BickEYTb2ji4ySSlpAZnlBZZFkSXOAJQyqNrEyBwA5ACkhgDMlsg6WADUPf3q0gT4qAB0CBPYPQAMAIKra5YEo7rMlhBNmz0A7ABCm6NXo8gIyaPMPQCsZ5zOzwAiExfr16NeAC9MGIduxRAQEON%2Bh9/nggagqBBmEd%2Bj8Nr9rm5iNtEX1DH0ngDtHihKpgBCUWjTh8ui1WCAuk8uqQDF0VszUAz1P82h1MOMBpxmQQGeymi0ANYgfr9OYy%2BUKxUANiEDO4zNZ7NInK6zOkIBWpBFbNppDgsBgiBQqF0bjw7DIFAgaFt9pKyGAzmMVHtBEc%2BogdlFzLslmSAE8GULSC7dKoCAB5WisSMm0hYPaidjB9N4YjZRQAN0w%2BrTmAAHtltH6c9s5DnWHg7MQI5osFHhdjdB2WjR6Ew2BwePxBMJRCAJGIpI27PrIC1UG54rRSwBaADqbFYow3jmIJD1cgLPhUakqBk4JjUhQiUUEHi8y/P9%2BCy5vxScl6yOQSNWfX6PH9aDyFJ3waT8ynyf9INAupbxKTgWmkXlOi4OkGSZFkcx1csAA4lVXJVuFGYBkGQUZnDmQxRggXBCBIAV%2BkvUZNFdB1GMQljhWDcVSClJ5DXpLp1VIbsBKwtMdT1A0jR4s1LQgJA2gINxq3ISgXTtB1BEwfAiAgvtGBYbNhwAdxbNwe1VRkNWwhk%2BiY0ZTMISE8IIoiSLIiiqO4k1eIQTBmCwJxDj4rgVkEtVmTEw1NQ5BlpMNY0xUlaVZUVDL5RVIT%2BlsySEtkvz5Pgc0rU0t1HQ0m0tPdYYRE9CLSB9Vg/WIAMgzTUNaAjDsYxtON6CTFMcwzerszTfB8xyYtSy1CsqxrNM6yErUZxbYhwzbbpowILsrMMgcTN4ARjDHcRJCEJs51CxdlzXTdWG3XdiH3YhDziE8IFMaDTDAu9LwfEJfC0dIX0fHw/oQmRAOXEDUhBgIAI%2B398khiDpighGLxg2pwg/NDWnaVDEOszC4u1Bk3MI4i6tEbyVjmFYaLo/SONIFjqoqxjDCaLjCpSsKZTlTKMuskSYokrUpJkGTktNUrFJAZTVIIdTnU57TjF0%2BiDLoIzBy4XhzOYSyuiFdCbMl%2BLegGajnIhUYqY82ngHpxnfIFgKgpKUKhPFkBxPJ6X9SSnjUqFkXRZyvKpYKuXeKEwwY%2Btj3aRaYs2pPbggA" rel="nofollow noreferrer">GodBolt</a>.</p>\n\n<hr>\n\n<p>Nonetheless, the division maintains safety, if the type significantly changes (although these cases are rare).</p>\n'}, {'answer_id': 68236983, 'author': 'Mano S', 'author_id': 16056201, 'author_profile': 'https://Stackoverflow.com/users/16056201', 'pm_score': -1, 'selected': False, 'text': '<p>For a predefined array:</p>\n<pre><code> int a[] = {1, 2, 3, 4, 5, 6};\n</code></pre>\n<p>Calculating number of elements in the array:</p>\n<pre><code> element _count = sizeof(a) / sizeof(a[0]);\n</code></pre>\n'}, {'answer_id': 72008351, 'author': 'Punisher', 'author_id': 10213913, 'author_profile': 'https://Stackoverflow.com/users/10213913', 'pm_score': -1, 'selected': False, 'text': '<p>To know the size of a fixed array declared explicitly in code and referenced by its variable, you can use <em>sizeof</em>, for example:</p>\n<pre><code>int a[10];\nint len = sizeof(a)/sizeof(int);\n</code></pre>\n<p>But this is usually useless, because you already know the answer.</p>\n<p><em>But</em> if you have a pointer you <em>can’t</em> use <em>sizeof</em>, its a matter of principle.</p>\n<p>But...Since arrays are presented as linear memory for the user, you can calculate the size if you know the last element address and if you know the size of the type, then you can count how many elements it have. For example:</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(){\n    int a[10];\n    printf(&quot;%d\\n&quot;, sizeof(a)/sizeof(int));\n    int *first = a;\n    int *last = &amp;(a[9]);\n    printf(&quot;%d\\n&quot;, (last-first) + 1);\n}\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>10\n10\n</code></pre>\n<p>Also if you can\'t take advantage of compile time you can:</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(){\n    int a[10];\n    printf(&quot;%d\\n&quot;, sizeof(a)/sizeof(int));\n    void *first = a;\n    void *last = &amp;(a[9]);\n    printf(&quot;%d\\n&quot;, (last-first)/sizeof(int) + 1);\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/37538', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/116/']