Domanda

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

Can someone please tell me what's wrong with this code? As is clear from the comments, I am just trying to implement the use of pointers and pointers variables. Among the other errors, I am getting a "Illegal Indirection error" in the (*addressOfVariable=10) code.

Thank You for your help.

È stato utile?

Soluzione

There is nothing wrong here with pointer or dereferencing operator (*). It seems that you are not compiling your code in C99 mode. In C89 mixed type declarations are not allowed.

EDIT: As OP said in his comment that he is using MS Visual Studio 2012, MSVC does't support C99 (basically it is a C++ compiler). You can't compile your code in C99 mode. Now declare all the variables in the beginning of the code like C89;

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

Altri suggerimenti

try this

    int y=4;
    int *addressOfVariable=&y;
    int memoryValue=*addressOfVariable;
    printf("\n Address of variable y is :%p\n",&y);
    *addressOfVariable=10;
    _getch();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top