[ACCEPTED]-Cannot take the address of the given expression C# pointer-pointers

Accepted answer
Score: 12

Is the error on my side?

No; the error is 22 in the documentation you linked to. It 21 states:

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

The comment is incorrect; as you 20 correctly note, it is not legal to take 19 the address of the interior of a string. It 18 is only legal to take the address of the 17 interior of an array.

The legal initializers 16 for a fixed statement are:

  • The address operator & applied to a variable reference.
  • An array
  • A string
  • A fixed-size buffer.

str[0] is not a variable 15 reference, because first, string elements 14 are not variables, and second, because this 13 is a call to an indexing function, not a 12 reference to a variable. Nor is it an array, a 11 string, or a fixed-size buffer, so it should 10 not be legal.

I'll have a chat with the documentation 9 manager and we'll see if we can get this 8 fixed in a later revision of the documentation. Thanks 7 for bringing it to my attention.

UPDATE: I 6 have spoken to one of the documentation 5 managers and they have informed me that 4 we have just passed the deadline for the 3 next scheduled revision of the documentation. The 2 proposed change will go in the queue for 1 the revision after next.

Score: 2

This doesn't work because you're trying 2 to access a string. If you change your code 1 to:

char[] mySentence = "Pointers in C#".ToCharArray();

fixed (char* start = &mySentence[0])
    char* p = start;

    while (*(++p) != '\0');


everything will work fine.

Score: 0

mySentence[0] returns a readonly single 1 character, you cannot get a pointer to that.


fixed(char* start = &mySentence)


More Related questions