How ptr arithmitic works??? It doesn't make any sense....

Salih Dincer salihdb at hotmail.com
Mon Dec 5 22:21:06 UTC 2022


On Monday, 5 December 2022 at 18:01:47 UTC, ag0aep6g wrote:
> You can use bracket notation with pointers. You just need to 
> move your closing parenthesis a bit.
>
> Assuming that `ptr` is a `void*`, these are all equivalent...

Yeah, there is such a thing!  I'm sure you'll all like this 
example:

```d
struct AAish(K, V, size_t s)
{
   K key;
   V[s] value; // 5 + 1(\0)

   string toString() {
     import std.format : format;
     import core.stdc.string : strlen;
     auto result = value[0..strlen(value.ptr)];
     return format("%s: %s", key, result);
   }
}

void stringCopy(C)(ref C src, string str) {
   import std.algorithm : min;
   auto len = min(src.length - 1,
                  str.length);
   src[0 .. len] = str[0 .. len];
   src[len] = '\0';
}

enum n = 9;
alias AA = AAish!(int, char, n);

void main()
{
   // First, we malloc for multiple AA()
   import core.stdc.stdlib;
   auto v = malloc(n * AA.sizeof);
   static assert(
     is (typeof(v) == void*)
   );

   // Cast to use memory space for AA()'s
   auto ptr = cast(AA*)v;
   static assert(
     is (typeof(ptr) == AA*)
   );

   // init AA()'s:
   foreach(i; 0..n)
   {
     ptr[i] = AA(i);
   }

   import std.stdio;
   ptr[0].value.stringCopy = "zero";
   ptr[0].writeln;

   ptr[1].value.stringCopy = "one";
   ptr[1].writeln;

   ptr[2].value.stringCopy = "two";
   ptr[2].writeln;

   ptr[3].value.stringCopy = "three";
   ptr[3].writeln;

   "...".writeln; //...

   ptr[8].value.stringCopy = "eight";
   ptr[8].writeln;

   ptr[0..n/2].writeln;
}
/* Prints:

0: zero
1: one
2: two
3: three
...
8: eight
[0: zero, 1: one, 2: two, 3: three]

*/
```
SDB at 79


More information about the Digitalmars-d-learn mailing list