Simple modification of C strings using pointers

♀尐吖头ヾ 提交于 2019-12-31 01:45:08

问题


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

#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 doesn't work. I'm sure I'm missing something obvious - I have very, very little experience with C.

Thanks for your help!


回答1:


You are attempting to modify a string literal. String literals are not modifiable (i.e., they are read-only).

A program that attempts to modify a string literal exhibits undefined behavior: the program may be able to "successfully" modify the string literal, the program may crash (immediately or at a later time), a program may exhibit unusual and unexpected behavior, or anything else might happen. All bets are off when the behavior is undefined.

Your code declares original_string as a pointer to the string literal "ABC":

char* original_string = "ABC";

If you change this to:

char original_string[] = "ABC";

you should be good to go. This declares an array of char that is initialized with the contents of the string literal "ABC". The array is automatically given a size of four elements (at compile-time), because that is the size required to hold the string literal (including the null terminator).




回答2:


The problem is that you can't modify the literal "ABC", which is read only.

Try char[] original_string = "ABC", which uses an array to hold the string that you can modify.



来源:https://stackoverflow.com/questions/2921376/simple-modification-of-c-strings-using-pointers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!