gpt4 book ai didi

c++ - s[j] = s[i];尝试复制字符时出现段错误

转载 作者:太空狗 更新时间:2023-10-29 23:35:07 25 4
gpt4 key购买 nike

我从某个地方找到了这个程序并试图理解它。

这一行:s[j++] = s[i]; 是崩溃的原因。我的理解是第一次至少程序不应该崩溃,因为 j 稍后会递增。第一次 j 和 i 的值将为 0。

所以,这就像 s[0] = s[0];

为什么会崩溃?

#include <iostream>

using namespace std;


void squeeze(char a[], char c);

int main()
{
squeeze("qwiert", 'i');

return 0;
}

void squeeze(char s[], char c)
{
int i, j;

for (i = j = 0; s[i] != '\0'; i++)
{
if (s[i] != c)
{
std::cout << "\ni: " << s[i];
s[j++] = s[i];
std::cout << "\nj: " << s[j];

std::cout << "\nj : " << j;
exit(0);
}
}

s[j] = '\0';
}

输出:

我:q

此后程序崩溃。

我已经放置了 exit 语句来停止指向查找段错误的程序。

最佳答案

不允许更改字符串文字,例如:

squeeze("qwiert", 'i');

标准的几乎所有迭代都涵盖了这一点(a):

  • C++03 2.13.4.String literals [lex.string]/2;
  • C++11 2.14.5.String literals [lex.string]/12;和
  • C++14 2.14.5.String literals [lex.string]/13

每个都存在相同的措辞:

Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation-defined. The effect of attempting to modify a string literal is undefined.

在最新的 C++17 标准中,措辞略有变化,但大致相同,目前为 C++17 5.13.5.String literals [lex.string]/16:

Whether all string literals are distinct (that is, are stored in nonoverlapping objects) and whether successive evaluations of a string-literal yield the same or a different object is unspecified. [Note: The effect of attempting to modify a string literal is undefined. - end note]

我建议你尝试这样的事情:

char str[] = "qwiert"; // Make a writable copy.
squeeze(str, 'i'); // then fiddle with that.

(a) 这个答案中的 ISO 引用实际上提供了一个关于为什么是这种情况的暗示。

我们并不总是拥有数 GB 的机器,而且通常情况下必须采取某些步骤在早期编译器中进行优化(主要是 C,但由于 C++ 的初始实现是 C 的前端,因此被推进到 C++ 中).

为此,具有相同字符(或以某些方式重叠的字符,例如 "successful""unsuccessful")的两个字符串可以共享相同的内存以减少空间。

当然,这意味着你不能在不影响另一个的情况下改变一个,这就是制定这条规则的原因。

关于c++ - s[j] = s[i];尝试复制字符时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47492659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com