【问题标题】:Pointer Address/Dereferencing operator指针地址/取消引用运算符
【发布时间】:2025-12-14 04:00:01
【问题描述】:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

int main()
{
  int y = 4; //This is a variable stored in the stack
  printf("\n Address of variable y is :%p\n", &y); // This is the address of the variable  y
  int *addressOfVariable = &y; //This is a pointer variable, a P.V stores the memory address of a variable
  //Read the value stored in a memory address
  int memoryValue = *addressOfVariable; //* is a dereference operator, it reads the value stored in a memory address and stores it in another variable
  //Update the value stored in the memory address
  *addressOfVariable = 10;
  _getch();
  return 0;
}

谁能告诉我这段代码有什么问题?从 cmets 可以清楚地看出,我只是想实现指针和指针变量的使用。在其他错误中,我在 (*addressOfVariable=10) 代码中收到“非法间接错误”。

感谢您的帮助。

【问题讨论】:

  • 除了conio.h/_getch 对我来说编译干净。你的编译器/环境是什么?
  • 对我也很好。如果我在最后打印y,它会显示10
  • 我在 Windows 上使用 MS Visual Studio 2012。我还收到“addressOfVariable undeclared identifier”错误。不知道为什么!
  • @BLUEPIXY:你能详细说明一下吗?
  • @self @user2981518: @BLUEPIXY 表示 MSVC 只允许 C89/C90 代码,其中语句和变量声明不能混用。函数体内的所有变量声明都必须位于新作用域的开头(紧接在{ 之后和与之匹配的} 之前)。在函数体的开头声明所有变量,MSVC会编译代码。

标签: c pointers dereference


【解决方案1】:

指针或取消引用运算符 (*) 没有任何问题。您似乎没有在 C99 模式下编译代码。在 C89 中,不允许混合类型声明。

编辑:正如 OP 在他的评论中所说,他正在使用 MS Visual Studio 2012,MSVC 不支持 C99(基本上它是一个 C++ 编译器)。你不能在 C99 模式下编译你的代码。现在像 C89 一样在代码开头声明所有变量;

int y=4;
int *addressOfVariable=&y;
int memoryValue=*addressOfVariable; 
....   

【讨论】:

    【解决方案2】:

    试试这个

        int y=4;
        int *addressOfVariable=&y;
        int memoryValue=*addressOfVariable;
        printf("\n Address of variable y is :%p\n",&y);
        *addressOfVariable=10;
        _getch();
    

    【讨论】:

    • 我不会投反对票,但我希望你意识到这不是一个完整的答案。它给出了正确的代码,但没有解释为什么它与问题中的代码相比是正确的。
    • @ChronoKitsune 我已经描述过了。但他不明白。所以显示了具体的代码。
    • 不知想到微软。为什么选择 2013 年的 C89?
    • @ChronoKitsune 我会因为认为它遇到了向上兼容。但它不同。
    • @BLUEPIXY - 没有任何解释,这个答案根本没有帮助。