Can't use keyword 'fixed' for a variable in C#

半城伤御伤魂 提交于 2021-02-09 05:28:48

问题


I tested the keyword fixed with array and string variables and worked really well but I can't use with a single variable.

static void Main() {

    int value = 12345;
    unsafe {
        fixed (int* pValue = &value) { // problem here
            *pValue = 54321;
        }
    }
}

The line fixed (int* pValue = &value) causes a complier error. I don't get it because the variable value is out of the unsafe block and it is not pinned yet.

Why can't I use fixed for the variable value?


回答1:


This is because value is a local variable, allocated on the stack, so it's already fixed. This is mentioned in the error message:

CS0213 You cannot use the fixed statement to take the address of an already fixed expression

If you need the address of value, you don't need the fixed statement, you can get it directly:

int* pValue = &value;


来源:https://stackoverflow.com/questions/32384525/cant-use-keyword-fixed-for-a-variable-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!