指针地址/解引用运算符

3
#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;
}

能否请有经验的人告诉我这段代码哪里出了问题?从注释可以看出,我只是想实现指针和指针变量的使用。除了其他错误之外,在 (*addressOfVariable=10) 代码中我得到了一个 "非法间接访问错误"。

谢谢您的帮助。


5
除了 conio.h/_getch ,我的编译器可以顺利编译。你用的是哪个编译器/环境? - Mat
2
对我来说也可以正常工作。如果我在结尾打印 y,它会显示 10 - Barmar
如果你正在使用MSVC编译器,那么在块变量声明的开始处将会有这个。 - BLUEPIXY
2
@BLUEPIXY:您能否再详细解释一下? - Manish Giri
1
@self @user2981518:@BLUEPIXY 的意思是 MSVC 只允许 C89/C90 代码,其中语句和变量声明不能混合。函数体内的所有变量声明必须在新作用域的开头(紧接着 { 并在其匹配的 } 之前)。在函数体的开头声明所有变量,MSVC 将编译代码。 - user539810
显示剩余5条评论
2个回答

3

指针或解引用运算符(*)没有任何问题。看起来你没有在C99模式下编译代码。在C89中,混合类型声明是不允许的。

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

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

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

2
我不会点踩,但我希望你意识到这不是一个完整的答案。它提供了正确的代码,但没有解释为什么它与问题中的代码相比是正确的。 - user539810
1
@ChronoKitsune 我已经描述过了,但他没有理解。所以请展示具体的代码。 - BLUEPIXY
MSVC是一种C++编译器。除了C++11标准所要求的内容,它为什么还应该支持C99呢? - user539810
1
@ChronoKitsune 我会这样认为,因为它遇到了向上兼容的情况。但是它并不相同。 - BLUEPIXY
1
@BLUEPIXY - 没有任何解释,这个答案就不是很有帮助。 - Roddy
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接