简体   繁体   English

使用指针简单修改C字符串

[英]Simple modification of C strings using pointers

I have two pointers to the same C string. 我有两个指向同一个C字符串的指针。 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. 如果我将第二个指针递增1,并将第二个指针的值赋给第一个指针的值,我希望第一个字符串的第一个字符可以改变。 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. 我敢肯定我错过了一些明显的东西 - 我对C的经验非常非常少。

Thanks for your help! 谢谢你的帮助!

You are attempting to modify a string literal. 您正在尝试修改字符串文字。 String literals are not modifiable (ie, 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" : 您的代码将original_string声明为指向字符串文字"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" . 这声明了一个char数组,它使用字符串文字"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). 数组自动给出四个元素的大小(在编译时),因为这是保存字符串文字所需的大小(包括空终止符)。

The problem is that you can't modify the literal "ABC", which is read only. 问题是你不能修改文字“ABC”,它是只读的。

Try char[] original_string = "ABC" , which uses an array to hold the string that you can modify. 尝试char[] original_string = "ABC" ,它使用数组来保存您可以修改的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM