指针地址/解除引用运算符

时间:2013-12-24 17:58:56

标签: c pointers dereference

#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)代码中收到“非法间接错误”。

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:1)

试试这个

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