不能采取定表达式C#指针的地址 [英] Cannot take the address of the given expression C# pointer

查看:737
本文介绍了不能采取定表达式C#指针的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑在不安全的上下文下面的代码:

 字符串mySentence =指针在C#; 

固定(字符*开始= mySentence)//这是我们谈论的
{
的char * p行=启动;


{
Console.Write(* P);
}
,而(!*(++ P)='\0');
}

到Console.ReadLine();

这工作不错。



http://msdn.microsoft.com/en-美国/库/ f58wzh21(v = VS.100)的.aspx 我应该能够取代我打上

 <$ C线$ C>固定(字符*开始=安培; mySentence [0])

不过遗憾的是VS给我下面的错误。




不能采取定表达式



的地址

是我这边的错误?



VS.NET 2010高级


解决方案

时的错误就在我身边。




没有?;错误的是您链接到的文件中。它指出:

 固定(的char * p = STR){/*...*/} //相当于P = &安培;海峡[0] 

注释不正确;因为你注意到,这是不合法的取一个字符串的内部地址。它是唯一合法的取阵列内部的地址



对于固定声明的法律初始化为:




  • 的地址运算符&安培; 应用于变量引用。

  • 阵列

  • 字符串

  • 一个固定大小的缓冲区。



海峡[0] 是不是一个变量引用,因为首先,字符串元素不是变量,和第二的,因为这是一个索引函数的调用,而不是一个变量的引用。它也不是一个数组,字符串或固定大小的缓冲区,所以它不应该是合法的。



我要的文件管理器和我们聊天会看到,如果我们能得到这个固定在文档的后续版本。感谢它带给我的注意。



更​​新:我曾与文档管理公司之一,他们已经通知我,我们刚刚通过的最后期限下一个计划文档修订。拟议的变化将走在队列的修订后年。


Consider the following code in an unsafe context:

string mySentence = "Pointers in C#";

fixed (char* start = mySentence) // this is the line we're talking about
{
    char* p = start;

    do
    {
        Console.Write(*p);
    }
    while (*(++p) != '\0');
}

Console.ReadLine();

This works good.

According to http://msdn.microsoft.com/en-us/library/f58wzh21(v=VS.100).aspx I should be able to replace the line I marked with

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

But unfortunately VS gives me the following error.

Cannot take the address of the given expression

Is the error on my side?

VS.NET 2010 Premium.

解决方案

Is the error on my side?

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

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

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

The legal initializers 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 reference, because first, string elements are not variables, and second, because this is a call to an indexing function, not a reference to a variable. Nor is it an array, a string, or a fixed-size buffer, so it should not be legal.

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

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

这篇关于不能采取定表达式C#指针的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆