Const Pointer in C
Level 5254 keystrokes
Compares three const placements: a pointer to const can be redirected but cannot change the value, a const pointer can change the value but not be redirected, and a const pointer to const allows neither. It prints 10, 20, then 30 twice after writing through ptr2.
C code
// Two ints the pointers will point to1int a = 10, b = 20;2 // Pointer to const: *ptr1 = ... is an error, but ptr1 may point elsewhere3const int *ptr1 = &a;// Const pointer: *ptr2 may be changed, but ptr2 always points to a4int *const ptr2 = &a;// Const pointer to const: neither the value nor the pointer can change5const int *const ptr3 = &a;6 // Reading through a pointer to const is fine: prints *ptr1: 107printf("*ptr1: %d\n", *ptr1);// Redirects ptr1 to b, which is allowed8ptr1 = &b;// ptr1 now points to b: prints *ptr1 after: 209printf("*ptr1 after: %d\n", *ptr1);10 // Writes 30 into a through the const pointer11*ptr2 = 30;// a itself changed: prints *ptr2: 30, a: 3012printf("*ptr2: %d, a: %d\n", *ptr2, a);13 // ptr3 can only read; it sees the new value of a: prints *ptr3: 3014printf("*ptr3: %d\n", *ptr3);Output
*ptr1: 10 *ptr1 after: 20 *ptr2: 30, a: 30 *ptr3: 30
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C code and how often they appear.
*× 12;× 10"× 8,× 7=× 7:× 5%× 5(× 4)× 4\× 4