LearnFrenzy
Sign in Take a free test

Declarations and Initializations · Declaration Programs · Question 6

String array vs string literal: modify a copy safely in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links