Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

3
  • 1
    Note that this will only work when the array definition is being seen by the compiler (that is either the array is global or within the same function). It will fail if the array is passed as argument to a function, and it will fail silently providing an erroneous answer. int f( char data[] ) { return sizeof(data)/sizeof(data[0]); } void caller() { char array[] = { 0 }; f(array) } will return the size of a pointer (usually 4/8) and not 1, which is the actual solution. This is because arrays decay into pointers at function calls when passed by value. Commented Jan 16, 2010 at 11:11
  • Tip: it's common to define a macro like this: #define ARRSIZE(arr) (sizeof(arr)/sizeof(*(arr))) to get the number of elements of an array whose size is known at compile time. Commented Jan 16, 2010 at 11:13
  • "this can't be used when you pass an array to a function" ... It can when using references. Commented Jan 16, 2010 at 11:16