c++ - 字符串的异常行为

标签 c++ c string

#include<stdio.h>
#include<iostream>
#include<cstring>
using namespace std;
int main(void)
{
    char a[10]="Rosewater";
    char b[3];

    int i=0;
    for(i=0;i<5;i++)
    {
        b[i]=a[i]; //1. does not throw an error
    }
    printf("%s\n%s\n",a,b);
}

输出:

ewsewater        // value of a also changed

Rosewsewater      // unclear output

最佳答案

//1. does not throw an error

CC++中没有边界检查,因为它只是暴露原始内存。

这被定义为未定义行为。 这意味着(很简单)标准没有指定程序中会发生什么,当指令产生未定义的行为时,任何事情都可能发生。

如果您使用C(这是与C不同的语言),我的建议是使用std::vector类。 Here References .

请注意,当您尝试访问越界索引时,std::vector 会产生未定义的行为。方法at ,相反,在这种情况下会抛出异常。

#include <vector>

int main(int argc, char* argv[]) {
  std::vector<char> a = {'a', 'b', 'c'};
  a.at(5);  // it will throw an exception
  return 0;
}

此外,如果您必须管理字符串,最方便的类是 std::string .

关于c++ - 字符串的异常行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39556762/

相关文章:

c++ - 在 C++ 中,如何获取格式为 "######"的字符串并将每个字符存储为整数?

c++ - 左值在使用 std::make_pair 时指定 const 对象

c++ - 两个进程之间如何通信

c++ - 如何存储指向 char * 缓冲区内某个位置的指针,发送到函数,检索值?

c - 在不使用 getpass (3) 的情况下在 C 中获取密码?

c - C 结构体中的结构体意味着什么?

ruby - Ruby 中带有未知标点符号的字符串拆分

c++ - 根据字符串表示设置枚举值

c++ - 如何使用数组查找标准差

在 C 中更改常量变量