Show the difference between a writable char array and a read-only literal by changing a copy of each.
Solution
main.c
#include <ctype.h>
#include <stdio.h>
int main(void) {
char greeting[] = "hello"; /* a writable copy in an array */
const char *literal = "hello"; /* points to a read-only literal */
greeting[0] = 'J';
char copy[16];
snprintf(copy, sizeof copy, "%s!", literal); /* change a copy, never the literal */
copy[0] = (char) toupper((unsigned char) copy[0]);
printf("%s %s %s\n", greeting, literal, copy);
return 0;
}
Output Verified by compiling and running
Jello hello Hello!
char greeting[] = "hello" declares an array initialised from the literal, so it can be changed. The literal itself must not be modified, so the program edits a copy.
More Declarations and Initializations practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!