Search code examples
c#pointersfixedunsafe

reassigning a pointer in csharp


I am having an issue trying to port the following code from C to C#. not having much success with using the fixed keyword and a ptr that gets reassigned. Could someone tell me how to represent the following code in c#?

        p = &table[(i = start[k]) >> m];
        i <<= tablebits;
        n = k - tablebits;
    /* make tree (n length) */
        while (--n >= 0) {
            if (*p == 0) {
                right[avail] = left[avail] = 0;
                *p = avail++;
            }
            if (i & 0x8000) p = &right[*p];
            else            p = &left[*p];
            i <<= 1;
        }
        *p = j;

Solution

  • Here goes using no pointers (C# safe)...

    var[] curtable = table;
    i = start[k];
    int idx = i >> m;
    
    i <<= tablebits;
    n = k - tablebits;
    
    /* make tree (n length) */
    while (--n >= 0) 
    {
        if (curtable[idx] == 0) 
        {
            right[avail] = left[avail] = 0;
            curtable[idx] = avail++;
        }
        if (i & 0x8000) 
        {
              idx = curtable[idx];
              curtable = right;
        }
        else  
        {
              idx = curtable[idx];
              curtable = left;
         }
        i <<= 1;
    }
    curtable[idx] = j;