How do I determine the size of my array in C?
Executive summary:
int a[17];
size_t n = sizeof(a)/sizeof(a[0]);
Full answer:
To determine the size of your array in bytes, you can use the sizeof
operator:
int a[17];
size_t n = sizeof(a);
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:
int a[17];
size_t n = sizeof(a) / sizeof(int);
and get the proper answer (68 / 4 = 17), but if the type ofa
changed you would have a nasty bug if you forgot to change
the sizeof(int)
as well.
So the preferred divisor is sizeof(a[0])
or the equivalent sizeof(*a)
, the size of the first element of the array.
int a[17];
size_t n = sizeof(a) / sizeof(a[0]);
Another advantage is that you can now easily parameterize
the array name in a macro and get:
#define NELEMS(x) (sizeof(x) / sizeof((x)[0]))
int a[17];
size_t n = NELEMS(a);
How do sizeof(arr) / sizeof(arr[0]) work?
If you have an array
then sizeof(array)
returns the number of bytes the array occupies. Since each element can take more than 1 byte of space, you have to divide the result with the size of one element (sizeof(array[0])
). This gives you number of elements in the array.
Example:
std::uint32_t array[10];
auto sizeOfInt = sizeof(std::uint32_t); // 4
auto numOfBytes = sizeof(array); // 10*sizeOfInt = 40
auto sizeOfElement = sizeof(array[0]); // sizeOfInt = 4
auto numOfElements = sizeof(array) / sizeof(array[0]); // numOfBytes / sizeOfElement = 40 / 4 = 10
LIVE EXAMPLE
Note that if you pass an array to a function, the above won't work since the array decays to a pointer and sizeof(array)
returns the size of the pointer.
std::size_t function(std::uint32_t a[]) // same for void function(std::uint32_t a[10])
{
return sizeof(a); // sizeof(std::uint32_t*)!
}
std::uint32_t array[10];
auto sizeOfArray = function(array); // array decays to a pointer inside function()
LIVE EXAMPLE #2
Can sizeof() be used to define an array length?
The sizeof expression is evaluated at compile time (by the compiler not the preprocessor) so the expression is legal.
There's an exception to this rule in C99 where dynamic arrays are allowed. In that case sizeof is, depending on context, evaluated at runtime (http://en.wikipedia.org/wiki/Sizeof). It doesn't change the legality of the expression in the question.
How to get the length of an array in C? Is sizeof a solution?
Arrays decay to pointers in function calls. It's not possible to compute the size of an array which is only represented as a pointer in any way, including using sizeof
.
You must add an explicit argument:
void show(int *data, size_t count);
In the call, you can use sizeof
to compute the number of elements, for actual arrays:
int arr[] = { 1,2,3,4,5 };
show(arr, sizeof arr / sizeof *arr);
Note that sizeof
gives you the size in units of char
, which is why the division by what is essentially sizeof (int)
is needed, or you'd get a way too high value.
Also note, as a point of interest and cleanliness, that sizeof
is not a function. The parentheses are only needed when the argument is a type name, since the argument then is a cast-like expression (e.g. sizeof (int)
). You can often get away without naming actual types, by doing sizeof
on data instead.
Sizeof returning incorrect array length
sizeof()
in encrypt
will not behave as you want it to. Inside encrypt
, the sizeof(char *)
is 4
(on a 32bit machine) or 8
(on a 64 bit machine), which you can see is the size of a pointer.
To get the sizeof(input)
you must change sizeof
to strlen
. Hence solution = strlen(input)
Why this happens?? when you pass an array into a function, that array is internally represented as a pointer. At the called-function's end input
is just a pointer, which gives either 4
or 8
bytesize depending upon your machine.
To get the sizeof
of input
, just use a macro like this: #define SIZEOF(x) (sizeof(x)/sizeof(x[0]))
and use this in the function that defines x
. In your program, x
is input
in main()
sizeof array without explicit length
Yes, the standard guarantees that the array element count will be equal to the number of elements in the array initializer in case no size is specified. See
C11 standard draft 6.7.9p22 and 6.7.9p25:
If an array of unknown size is initialized, its size is determined by
the largest indexed element with an explicit initializer. The array
type is completed at the end of its initializer list.EXAMPLE 2 The declaration
int x[] = { 1, 3, 5 };
defines and initializes
x
as a one-dimensional array object that has three elements, as no size was specified and there are three initializers.
How do I find the length of an array?
If you mean a C-style array, then you can do something like:
int a[7];
std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;
This doesn't work on pointers (i.e. it won't work for either of the following):
int *p = new int[7];
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
or:
void func(int *p)
{
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
}
int a[7];
func(a);
In C++, if you want this kind of behavior, then you should be using a container class; probably std::vector
.
Size of an array is different in the main function and user-defined functions
You get that behaviour because, in the C language the function declaration
void printArraySize(int array[])
is equivalent to
void printArraySize(int *array)
And therefore the value of the line int size = sizeof(array) / sizeof(array[0]);
on a program compiled for 32-bit where sizeof(int) == 4
is always 1.
Arrays cannot be passed to functions as arrays, but as pointers. In fact, if you try to modify array
in the printArraySize
function you will modify it also in the caller function main
.
And that's why strings in C (and in many other programming languages) are 0-terminated.
size of array in c
C arrays don't store their own sizes anywhere, so sizeof
only works the way you expect if the size is known at compile time. malloc()
is treated by the compiler as any other function, so sizeof
can't tell that arr
points to the first element of an array, let alone how big it is. If you need to know the size of the array, you need to explicitly pass it to your function, either as a separate argument, or by using a struct containing a pointer to your array and its size.
Related Topics
Addition of Two Pointers in C or C++ Not Supported. Why
How Serious Is the New/Delete Operator Mismatch Error
Invalid Initialization of Non-Const Reference with C++11 Thread
How to Make an Image Resize to Scale in Qt
Segmentation Fault with Char Array and Pointer in C on Linux
Why Can't I Access a Protected Member from an Instance of a Derived Class
Why Doesn't the C++11 'Auto' Keyword Work for Static Members
Legality of Using Operator Delete on a Pointer Obtained from Placement New
Cuda Linking Error - Visual Express 2008 - Nvcc Fatal Due to (Null) Configuration File
How to Print a String to the Console at Specific Coordinates in C++
What's the Real Reason to Not Use the Eof Bit as Our Stream Extraction Condition
How Disastrous Is Integer Overflow in C++
Error: Cannot Convert 'Const Wchar_T [13]' to 'Lpcstr {Aka Const Char*}' in Assignment
Does Std::Cout Have a Return Value