To have an idea what is __const__ in one char pointer declaration, read it from right to left.
- const char *p
- p is a pointer to a const char, it is same as “char const *p.
- you can change the value of p and get it to point to different constant characters. But whatever p points to, you can not change the contents.
- char * const p
- p is a const pointer to a char
- you are unable to change the pointer, but can change the contents.
Example 1
if it good to do:
norm = str;
norm = “AUTO”.
if you define norm this way:
const char *norm = “NSTC_J”;
char str[] = “PAL_M”;
However, both will fail with error “assignment of read-only variable ‘norm’”, if you define
char * const norm = “NSTC_J”,
Example 2
I have
struct norm_val {
char *norm;
Int reg_val;
};
struct norm_val set_norms[]= {
{“AUTO”, 0}
{“NTSC_J”, 0x10}
{“PAL_M”, 0x40}
{NULL, 0}
};
As we want to keep the contents of set_norms[i].norm unmodifiable, we need define “norm” as a pointer to a const char: const char *norm;
At the same time, we don’t want set_norm[i].norm points to somewhere else, we need define “norm” as a const pointer: char * const norm;
Moreover, we don’t want the entire content of set_norms[] being changed, either “norm” pointer, or “reg-val” value, we need define the set_norms as const (by doing this, we don’t need explicitly define “norm” to a const pointer).
struct norm_val {
const char *norm;
int reg_val;
} ;
const struct norm_val set_norms[]= {
{“AUTO”, 0}
{“NTSC_J”, 0x10}
{“PAL_M”, 0x40}
{NULL, 0}
};
Or
const struct {
const char *norm;
int reg_val;
} set_norms[]= {
{“AUTO”, 0}
{“NTSC_J”, 0x10}
{“PAL_M”, 0x40}
{NULL, 0}
};