Character arrays and character pointers can both read null-terminated strings, but they differ in storage ownership. An array owns a character copy; a pointer may refer to a string literal. String literals must not be modified, so prefer const char * to express read-only intent.
#include <stdio.h>
int main(void) {
char s1[] = "hello";
s1[0] = 'H';
printf("%s\n", s1); // Hello
const char *s2 = "hello";
// s2[0] = 'H'; // wrong: do not modify a string literal
printf("%s\n", s2);
return 0;
}KNOWLEDGE QUIZ
Array copies and string literals
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
Assigning string pointers
Pointer assignment does not copy characters; it copies only the address. Reassigning first to another literal leaves second holding the old address. To copy characters, use a sufficiently large character array and a function such as strcpy.
const char *first = "red";
const char *second = first;
first = "blue";
printf("%s\n", first); // blue
printf("%s\n", second); // redKNOWLEDGE QUIZ
Modify the first character of an array
Implement uppercase_first(char text[]). When the string is non-empty, modify text[0] with toupper. Test with char word[] = "leaflet" and print Leaflet.
- Use a char * parameter and check the pointer and first character.
- Convert the first character only when it is lowercase.
- Call the function with a character array and print the result.
Return a pointer to the longer string
Implement const char *longer(const char *a, const char *b). Use strlen and return the address of the longer string. Test with cat and telescope without copying characters.
- Accept two read-only character pointers.
- Measure both lengths with strlen.
- Return a or b from the comparison and print it in the caller.