Pointers and Strings: The Power of const in C
When passing strings to functions in C, the placement of the const keyword completely changes how the compiler protects your memory.
Consider this classic example:
#include <stdio.h>
void greet(const char *name) {
printf("Hello, %s!\n", name);
}
int main(void) {
greet("C Learner");
return 0;
}
Protecting Read-Only Memory
In C, strings passed in double quotes (like "C Learner") are string literals, which are typically stored by the compiler in read-only memory segments. If a function attempts to alter a character within a read-only string literal, it triggers a runtime crash known as a segmentation fault. Specifying const tells the compiler that the data must not be altered, allowing it to catch these programming mistakes at compile time instead of failing at runtime.
The Three Levels of Pointer Protection
The exact placement of the const keyword dictates what is protected:
- Pointer to Constant Data (
const char *name) The data (the characters) cannot be changed, but the pointer itself can still be reassigned to point to a different memory address. This is the format used in ourgreetfunction. - Constant Pointer (
char *const name) The pointer address is locked and cannot change. However, the data it points to remains fully modifiable, provided it points to writable memory like a stack array. - Constant Pointer to Constant Data (
const char *const name) Both doors are locked. You can neither change the address the pointer holds nor modify the characters it points to.
Quick Reference Guide
| Declaration | Can Modify Characters? | Can Reassign Pointer? |
|---|---|---|
const char *name |
No | Yes |
char *const name |
Yes | No |
const char *const name |
No | No |