constant pointer failing to compile

Salih Dincer salihdb at hotmail.com
Thu Apr 6 19:18:18 UTC 2023


On Thursday, 6 April 2023 at 00:46:26 UTC, Josh Holtrop wrote:
> ```
> constarrptr.d(5): Error: cannot use non-constant CTFE pointer 
> in an initializer `cast(immutable(ubyte)*)data`
> ```
>
> Why? And how can I do the equivalent to what I have been doing 
> in C? I want these pointers to be generated at compile time, 
> not initialized at runtime.
>
> (the full project is generating this file containing the data 
> array (which is much longer) and multiple pointer constants to 
> locations within it)

You have 2 options: First, to use .ptr, or second, to do the 
initialization in static this:

```d
import std.stdio;

static const char[] d;
static const char * p;

static this() {
   d = [97, 98, 99];
   p = &d[0]; // == d.ptr;
}

void main()
{
   printf("%.*s\n", cast(int)d.length, d.ptr);
   writeln("*p = ", *p);
}/* Prints:

   abc
   *p = a

*/
```

SDB at 79




More information about the Digitalmars-d-learn mailing list