9

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?

3

4 Answers 4

7

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;
}
Sign up to request clarification or add additional context in comments.

Comments

4

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.

1 Comment

"Return values from methods does not have an address." is not quite true - it just happened that return of string[int] is char that is not type that can be "fixed".
1

The point of the fixed statement is to prevent a memory allocation from moving across virtual memory. The memory allocation is identified by its beginning, not by any other address.

So to keep &str[1] fixed, you really need the whole str fixed; you can then use pointer arithmetic to derive other pointers within the single allocation from the fixed pointer to str as you wish.

Comments

-1

Change your code to this:

char[] strC = "1234".ToArray();
fixed (char* c = &strC[0])
{
    /// .....
}

1 Comment

This gives an address that points to a memory location that holds the first character, but it cannot be used to access other characters of the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.