0

why isn't *p = 0; and q = NULL; allowed? I know becauce Pointer is const but i don't know why exactly NULL at q and 0 at *p?

const int i = 0;
const int *p = &i;

int j = 0;
int * const q = &j;

// *p = 0; // Fehler, *p konstant
p = NULL;

*q = 0;
// q = NULL; // Fehler, q konstant

return 0;
  • Cannot reproduce, how do you compile and which compiler do you use? Also [edit] and show a [mcve] as well as the verbatim error log – Jabberwocky Apr 21 '22 at 10:31
  • With `p` the data it points to is constant (so assignment of the data: `*p=0`, fails), and with `q` the pointer itself is constant so you cannot assign to it. – wohlstad Apr 21 '22 at 10:35
  • 1
    See more here: https://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const – wohlstad Apr 21 '22 at 10:36
  • 1
    Check out this previously answered question: https://stackoverflow.com/questions/21476869/constant-pointer-vs-pointer-to-constant – carce-bo Apr 21 '22 at 10:36

2 Answers2

1

const int * p declare p as pointer to const int,

So the int pointed by p can't change, but you can modify p if it still points to a const int.


int * const q declare q as const pointer to int.

q on the contrary can't change, but the value pointed can.


You can use cdecl to understand C declarations:

~$ cdecl
cdecl> explain  const int *  p
declare p as pointer to const int
cdecl> explain  const int *  q
declare q as pointer to const int
cdecl>
Mathieu
  • 7,837
  • 6
  • 30
  • 43
1
const int *p = &i;

Here p is non-const pointer to const int. As the pointer itself is not const, you can set it to point to something else like NULL, but what it points to is const, so you can't modify it through this pointer.


int * const q = &j;

Here q is const pointer to non-const int. It is initialized to point to j, and you can't change what it points to. But you can change what it points to through it.


const int * const r = &j;

This would be const pointer to const int. So you can't change what it points to, and you can only read the value of what it points to, not change it.

the busybee
  • 8,244
  • 3
  • 12
  • 29
hyde
  • 55,609
  • 19
  • 114
  • 170