c - was bedeutet diese 2 const?
Code
const char * const key;
Es gibt 2 const im obigen Zeiger, ich habe solche Dinge das erste Mal gesehen.
Ich weiß, dass die erste Konstante den Wert, auf den der Zeiger zeigt, unveränderlich macht, aber hat die zweite Konstante den Zeiger selbst unveränderlich gemacht?
Kann jemand helfen, dies zu erklären?
@Aktualisieren
Und ich habe ein Programm geschrieben, das die Richtigkeit der Antwort bewiesen hat.
#include <stdio.h>
void testNoConstPoiner() {
int i = 10;
int *pi = &i;
(*pi)++;
printf("%d\n", i);
}
void testPreConstPoinerChangePointedValue() {
int i = 10;
const int *pi = &i;
// this line will compile error
// (*pi)++;
printf("%d\n", *pi);
}
void testPreConstPoinerChangePointer() {
int i = 10;
int j = 20;
const int *pi = &i;
pi = &j;
printf("%d\n", *pi);
}
void testAfterConstPoinerChangePointedValue() {
int i = 10;
int * const pi = &i;
(*pi)++;
printf("%d\n", *pi);
}
void testAfterConstPoinerChangePointer() {
int i = 10;
int j = 20;
int * const pi = &i;
// this line will compile error
// pi = &j
printf("%d\n", *pi);
}
void testDoublePoiner() {
int i = 10;
int j = 20;
const int * const pi = &i;
// both of following 2 lines will compile error
// (*pi)++;
// pi = &j
printf("%d\n", *pi);
}
int main(int argc, char * argv[]) {
testNoConstPoiner();
testPreConstPoinerChangePointedValue();
testPreConstPoinerChangePointer();
testAfterConstPoinerChangePointedValue();
testAfterConstPoinerChangePointer();
testDoublePoiner();
}
Unkommentierungszeilen in 3 der Funktionen führen zu Kompilierungsfehlern mit Tipps.