What is the difference in this example of Dereferencing pointers?

Viewed 52

So my class has two examples, and not sure why one works and the other doesn't.

int numSides = 3;
int *valPointer = &numSides;
PrintValue(valPointer);

Prints 3.

int numSides = 3;
int* valPointer;
*valPointer = &numSides;
PrintValue(valPointer);

This doesn't work, but why?

class note say int value can't be assigned int*.

3 Answers
int* valPointer;
*valPointer = &numSides;

The above is wrong -- you are trying to set (the integer-that-valPointer-points-to) to an address, which doesn't make sense, because addresses and integers are (generally speaking) not interchangeable.

Perhaps you meant this instead?

int* valPointer;
valPointer = &numSides;

... that would set valPointer to point to numSides.

The program:

void PrintValue(int*);

void f() {
  int numSides = 3;
  int *valPointer;
  *valPointer = &numSides;
  PrintValue(valPointer);
}

Compilation results:

Clang:

<source>:6:17: error: incompatible pointer to integer conversion assigning to 'int' from 'int *'; remove &
  *valPointer = &numSides;
                ^~~~~~~~~
1 error generated.
Compiler returned: 1

Gcc:

<source>: In function 'void f()':
<source>:6:17: error: invalid conversion from 'int*' to 'int' [-fpermissive]
    6 |   *valPointer = &numSides;
      |                 ^~~~~~~~~
      |                 |
      |                 int*
Compiler returned: 1

Microsoft compiler:

example.cpp
<source>(6): error C2440: '=': cannot convert from 'int *' to 'int'
<source>(6): note: There is no context in which this conversion is possible
Compiler returned: 2

Each compiler in it's own way says what the problem is in the error messages.

  • incompatible pointer to integer conversion assigning to 'int' from 'int *'
  • invalid conversion from 'int*' to 'int'
  • cannot convert from 'int *' to 'int'

Clang even gives a suggestion:

  • remove '&'

Which is not necessarily correct.

int *valPointer = &numSides;

This declares a variable, valPointer, of type int *, and stores the address of numSides in it.

int* valPointer; *valPointer = &numSides;

This declares a variable, valPointer, of type int *, but doesn't initialize it to point to any particular location. The address it contains is just whatever garbage happened to be on the stack. It then dereferences valPointer, which is an error because valPointer was never initialized, and tries to store the address of numSides in that location.

I think the essential point you need is that * is used to dereference a pointer when used alone (e.g. *valPointer), but it's part of the type when used in a declaration (e.g. int *valPointer). Also, note that when used in a declaration it doesn't matter whether there's space between the type and * or the * and variable; that is, int *foo and int *foo mean the same thing.

Related