constant pointer failing to compile

Josh Holtrop jholtrop at gmail.com
Thu Apr 6 00:46:26 UTC 2023


I am trying to port a small C project to D and am getting a 
compilation error I don't understand.

I've simplified the situation down to the example here.

This C version compiles fine:

```c
#include <stdio.h>

static const unsigned char data[] = {1, 2, 3, 4};

static const unsigned char * p = &data[0];

int main(int argc, char * argv[])
{
     printf("*p = %u\n", *p);
     return 0;
}
```

My attempt to do the same in D:

```d
import std.stdio;

__gshared immutable ubyte[] data = [1, 2, 3, 4];

__gshared immutable ubyte * p = data.ptr;

int main()
{
     writeln("*p = ", *p);
     return 0;
}
```

This fails to compile with gdc:

```
constarrptr.d:5:45: error: cannot use non-constant CTFE pointer 
in an initializer ‘&[cast(ubyte)1u, cast(ubyte)2u, cast(ubyte)3u, 
cast(ubyte)4u][0]’
     5 | __gshared immutable(immutable(ubyte) *) p = data.ptr;
       |                                             ^
```

And also with ldc2:

```
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)


More information about the Digitalmars-d-learn mailing list