As string String literals are constant , they and should only be assigned to constant pointers. This recommendation supports rule STR30-C.
...
Code Block |
---|
|
char * c = "Hello"; //* Bad: assigned to non-const */
c[3] = 'a'; //* Undefined (but compiles) */
|
Compliant Solution 1
If you properly assign string literals to const
pointers, the The compiler will not allow direct manipulation of the contents of string literals that are assignhed to const
pointers.
Code Block |
---|
|
char const * c = "Hello"; //* Good */
//c[3] = 'a'; would cause a compile error
|
...
Code Block |
---|
|
char * CMUfullname = "Carnegie Mellon";
/* get school from user input and validate */
if (strcmp(school,"CMU")) {
school = CMUfullname;
}
|
...
Code Block |
---|
|
char const * CMUfullname = "Carnegie Mellon";
/* get school from user input and validate */
if (strcmp(school,"CMU")) {
school = CMUfullname;
}
|
...
Code Block |
---|
|
char const * CMUfullname = "Carnegie Mellon";
/* get school from user input and validate */
if (strcmp(school,"CMU")) {
//assuming school is properly allocated
strcpy(school, CMUfullname);
}
|
...