Simple modification of C strings using pointers

I have two pointers to the same line C. If I increment the second pointer by one and assign the value of the second pointer to the first, I expect the first character of the first line to be changed. For instance:

#include "stdio.h"

int main() {
  char* original_str = "ABC";        // Get pointer to "ABC"
  char* off_by_one = original_str;   // Duplicate pointer to "ABC"
  off_by_one++;                      // Increment duplicate by one: now "BC"
  *original_str = *off_by_one;       // Set 1st char of one to 1st char of other
  printf("%s\n", original_str);      // Prints "ABC" (why not "BBC"?)
  *original_str = *(off_by_one + 1); // Set 1st char of one to 2nd char of other
  printf("%s\n", original_str);      // Prints "ABC" (why not "CBC"?)

  return 0;
}

This does not work. I am sure I am missing something obvious - I have very little experience with C.

Thank you for your help!

+3
source share
2 answers

You are trying to change a string literal. String literals are not modified (i.e., they are read-only).

, , undefined: "" , ( ), , - . , undefined.

original_string "ABC":

char* original_string = "ABC";

:

char original_string[] = "ABC";

. char, "ABC". ( ), , ( ).

+10

, "ABC", .

char[] original_string = "ABC", , .

+1

Source: https://habr.com/ru/post/1747370/


All Articles