Search code examples
c#indexingintptr

Cannot apply indexing to an expression of type 'IntPtr' == IntPtr ptr1 = [...] --> ptr1[0]


I found a code snippet which I want to implement. Now is the problem that one function isn't running. Cannot apply indexing to an expression of type 'IntPtr'

        fixed (byte* numRef = this.tribuf)
        {
            for (int i = 0; i < num; i++)
            {
                item = this.trihash.GetItem(ch + S.Substring(i, 3));
                if (item != null)
                {
                    this.TrigramChecked += item.Count;
                    foreach (int num3 in item)
                    {
                        if ((num3 != id) && (numRef[num3] < 0xff))
                        {
                            IntPtr ptr1 = (IntPtr) (numRef + num3);
                            /* ToDo: Error */
                            ptr1[0] = (IntPtr) ((byte) (ptr1[0] + 1));
                        }
                    }
                }
            }
        }

regards Chris


Solution

  • As I said in a comment, I would try to avoid unsafe code in the first place, but it looks like it's really just trying to do:

    if ((num3 != id) && (numRef[num3] < 0xff))
    {
        numRef[num3]++;
    }
    

    Or perhaps more efficiently (to only read from numRef[num3] once):

    if (num3 != id)
    {
        byte value = numRef[num3];
        if (value < 0xff)
        {
            numRef[num3] = (byte) (value + 1);
        }
    }