Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof in D language

Tags:

sizeof

size

d

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?

like image 842
Vlad Avatar asked Jun 30 '14 15:06

Vlad


People also ask

What is sizeof () operator?

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.

What is the sizeof int?

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.

Is sizeof a function or operator?

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.

What is sizeof return in C?

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.


2 Answers

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.

like image 178
Jonathan M Davis Avatar answered Oct 19 '22 11:10

Jonathan M Davis


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.

like image 40
ratchet freak Avatar answered Oct 19 '22 10:10

ratchet freak