Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsafe string pointer statement

As I understood, according to MSDN C# fixed statement should work like:

fixed (char* p = str) ... // equivalent to p = &str[0]

so, why I can`t do this?

    const string str = "1234";
    fixed (char* c = &str[0])
    {
/// .....
    }

How can I get pointer to str[1], for an example?

like image 720
Dzmitry Martavoi Avatar asked Apr 10 '13 07:04

Dzmitry Martavoi


2 Answers

Since obtaining a pointer to a later element directly works with arrays, but not with strings it seems like the only reason is that MS didn't implement it. It would have been easily possible to design it like that, following the semantics of arrays.

But you can easily compute another pointer that points at other array elements. So it's not a big issue in practice:

fixed (char* p = str)
{
   char* p1 = p+1;
}
like image 122
CodesInChaos Avatar answered Oct 06 '22 14:10

CodesInChaos


This is because the [] operator on the string is a method that returns a value. Return value from a method when it is a primitive value type does not have an address.

[] operator in C# is not the same as [] in C. In C, arrays and character strings are just pointers, and applying [] operator on a pointer, is equivalent to moving the pointer and dereferencing it. This does not hold in C#.

Actually there was an error in the MSDN documentation you linked, that is fixed in the latest version.

See here for more explanation on this exact matter.

like image 42
Mohammad Dehghan Avatar answered Oct 06 '22 15:10

Mohammad Dehghan