Counting an initialised array, and segments

Cecil Ward cecil at cecilward.com
Mon Jun 26 11:08:06 UTC 2023


On Monday, 26 June 2023 at 08:26:31 UTC, Jonathan M Davis wrote:
> On Sunday, June 25, 2023 4:08:19 PM MDT Cecil Ward via 
> Digitalmars-d-learn wrote:
>> I recently had some problems
>>
>> dchar[] arr = [ ‘ ‘, TAB, CR, LF … ];
>>
>> and I got errors from the compiler which led to me having to
>> count the elements in the initialiser and declare the array 
>> with
>> an explicit size. I don’t want the array to be mutable so I 
>> later
>> added immutable to it, but that didn’t help matters. At one
>> point, because the array was quite long, I got the arr[
>> n_elements ] number wrong, it was too small and the remainder 
>> of
>> the array was full of 0xffs (or something), which was good,
>> helped me spot the bug.
>>
>> Is there any way to get the compiler to count the number of 
>> elements in the initialiser and set the array to that size ? 
>> And it’s immutable.
>
> Without seeing the errors, I can't really say what the problem 
> was, but most character literals are going to be char, not 
> dchar, so you may have had issues related to the type that the 
> compiler was inferring for the array literal. I don't recall at 
> the moment how exactly the compiler decides the type of an 
> array literal when it's given values of differing types for the 
> elements.
>
> Either way, if you want a static array, and you don't want to 
> have to count the number of elements, then 
> https://dlang.org/phobos/std_array.html#staticArray should take 
> care of that problem.
>
> - Jonathan M Davis

Where I used symbolic names, such as TAB, that was defined as an 
int (or uint)
enum TAB = 9;
or
enum uint TAB = 9;
I forget which. So I had at least one item that was typed 
something wider than a char.

I tried the usual sizeof( arr )/ sizeof dchar, compiler wouldn’t 
have that for some reason, and yes I know it should be D syntax, 
god how I long for C sizeof()!


More information about the Digitalmars-d-learn mailing list