Search code examples
c#.netcompiler-errorsintptr

C# CS0019 IntPtr


I encountered a snippet of C# source code as following

int* ptr = ...;
int  w = ...;

int* ptr3 = ptr + (IntPtr)w;

CS0019: Operator '+' cannot be applied to operands of type 'int*' and 'System.IntPtr'

I guess this code was trying to move the ptr address forward by w which is dependent on the OS. Is this correct and how can I make this code compile?


Solution

  • No, it is not correct syntax. It is very unclear what you are trying to accomplish so just guessing here. If you want to move the pointer forward by "w" ints then use:

      int* ptr3 = ptr + w;
    

    Which adds 4*w to the pointer value since an int is 4 bytes. This is equivalent to treating ptr3 as a pointer into an array of ints where w is the array element offset. And the way the C language treats pointers.

    If you meant to increment the address by w then avoid using IntPtr, the C# language forbids using the + operator on an IntPtr, even though that's permitted by the CLR. You'll need to do some casting instead:

      int* ptr3 = (int*)((byte*)ptr + w);