import std.stdio;
void main() {
int[] a = [1,2,3,4,5,6,7,8,9,10];
write(a.sizeof);
}
In following code sizeof of static array is equals to 8 byte. I use x86 Windows 8, so pointer is equals to 4 byte. Why I get 8 byte size of array?
sizeof(int); The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding. Using the sizeof operator with a fixed-point decimal type results in the total number of bytes that are occupied by the decimal type.
So, the sizeof(int) simply implies the value of size of an integer. Whether it is a 32-bit Machine or 64-bit machine, sizeof(int) will always return a value 4 as the size of an integer.
In C language, sizeof( ) is an operator. Though it looks like a function, it is an unary operator. For example in the following program, when we pass a++ to sizeof, the expression “a++” is not evaluated. However in case of functions, parameters are first evaluated, then passed to function.
When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type. The output can be different on different machines like a 32-bit system can show different output while a 64-bit system can show different of same data types.
Because int[]
is a dynamic array, not a pointer. Arrays in D are not pointers. What they are is essentially
struct(T)
{
T* ptr;
size_t length;
}
So, if you want the underlying pointer, you need to use the array's ptr
member, though that's usually only needed when interacting with C/C++ code (since dynamic arrays in C/C++ are just pointers). However, the length
member is used all the time and helps make arrays in D far more powerful and pleasant to work with than arrays in C/C++ are. If you want to know more about arrays in D, then you should read this article. It goes into a fair bit of detail about them, and I would consider it a must-read for all D programmers.
Regardless, what sizeof
is giving you is the size of ptr
and length
together, which would be 8
on 32-bit systems, and 16
on 64-bit systems.
A dynamic array (what you have) is behind the scenes actually a struct with a pointer and a size_t
length both being 4 on your CPU.
This allows D to carry along the length of the array to avoid out of bounds reading and writing (if you have the check enabled) and a O(1)
slice operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With