This questions has been addressed here.
The suggested duplicate and the currently given answers don't address why there aren't issues with the examples given first. Mainly why doesn't the reasoning:
"const int ** is a pointer to const int *
which is a different thing from just int*
"
also apply for:
"const int * is a pointer to const int
which is a different thing from just int
"
I am approaching it from a different angle to hopefully get another explanation.
The code with the examples.
#include <stdio.h>
void f_a (int const a){
/*
* Can't do:
* a = 3; //error: assignment of read-only parameter ‘a’
*
* Explanation: I can't change the value of a in the scope of the function due to the const
*/
printf("%d
", a);
}
void f_ptr_a_type1 (int const * ptr_a){
/*
* Can do this:
* ptr_a’ = 0x3;
* which make dereferencig to a impossible.
* printf("%d
", * ptr_a’); -> segfault
* But const won't forbid it.
*
* Can't do:
* *ptr_a’ = 3; //error: assignment of read-only parameter ‘* ptr_a’
*
* Explanation: I can't change the value of a by pointer dereferencing and addignment due to the int const
*/
}
void f_ptr_a_type2 (int * const ptr_a){
/*
* Can do this:
* *a = 3;
*
* Can't do:
* ptr_a = 3; //error: assignment of read-only parameter ‘ptr_a’
*
* Explanation: I can't change the value because the const is protecting the value of the pointer in the funcion scope
*/
}
void f_ptr_ptr_a (int const ** ptr_ptr_a){
/*
* Can do this:
* ptr_ptr_a = 3;
* * ptr_ptr_a = 0x3;
*
* Can't do:
* ** ptr_ptr_a = 0x3; //error: assignment of read-only parameter ‘**ptr_a’
*
* Explanation: Makes sense. Just follows the pattern from previous functions.
*/
}
int main()
{
int a = 7;
f_a(a);
int * ptr_a = &a;
f_ptr_a_type1(&a);
f_ptr_a_type2(&a);
int ** ptr_ptr_a = &ptr_a;
f_ptr_ptr_a(ptr_ptr_a); //warning: passing argument 1 of ‘f_ptr_ptr_a’ from incompatible pointer type [-Wincompatible-pointer-types]
}
The accepted widely accepted answer goes something like this:
int ** isn't the same as const int** and you can't safely cast it
My question is why does the function suddenly care?
It didn't complain here that int
isn't int const
:
int a = 7;
f_a(a);
It didn't complain here because int *
isn't neither int const *
nor int * const
:
int * ptr_a = &a;
f_ptr_a_type1(&a);
f_ptr_a_type2(&a);
But suddenly it starts complaining in the double pointer case.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…