【问题标题】:Segmentation fault in c array, access to individual char in a string [duplicate]c数组中的分段错误,访问字符串中的单个字符[重复]
【发布时间】:2019-05-16 21:31:01
【问题描述】:

我正在尝试操作字符串中的单个字符,在这种情况下将第 4 个“a”更改为“b”。

string password = "aaaaa";
printf("password: %s\n",password);

int j = 'b';
password[3] = (char) j;
printf("password: %s\n",password);

返回:

密码:aaaa

分段错误

最后一点:在第一行中,我将“字符串”声明为变量。 CS50 库允许这种设计 - 它应该可以工作并且我过去曾使用过它。

提前谢谢你。

【问题讨论】:

  • 感谢您的 cmets - 我现在更新了标签。是的,我正在做出色的 cs50 并包含 #include

标签: c string char segmentation-fault cs50


【解决方案1】:

"aaaaa";String Literal,它在大多数系统上是不可变的,因此 password[3] = (char) j; 尝试修改不可变对象会导致 SegFault。

相反,

char password[] = "aaaaa";

假设您的"string"char*typedef,使用复合文字 可以得到相同的结果,例如:

string password = (char[]){"aaaaa"};

【讨论】:

  • 已经搞定了,非常感谢。
  • 当然,很高兴为您提供帮助。祝你编码顺利。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 1970-01-01
  • 2015-03-27
  • 1970-01-01
相关资源
最近更新 更多