【问题标题】:Initialization of character array inside constructor (Array Index Out of Bounds) in C++在 C++ 中初始化构造函数内的字符数组(数组索引超出范围)
【发布时间】:2020-12-11 20:08:01
【问题描述】:

我正在尝试在构造函数中初始化这两个字符数组。错误在于字符数组 buf 和 clientip,其他都很好。我在下面添加了整个构造函数的代码:

class server : public udp {

public:
    server() {

        clientLength = 0;
        buf[1024] = {};
        bytesIn = 0;
        count = 0;
        clientIp[256] = {};
        portnumber = 0;
    }

private:
    
    int clientLength = sizeof(client);
    char buf[1024];
    int bytesIn;
    int count = 0;
    char clientIp[256];
    unsigned short portnumber = 70000;

警告是:

*(error) 在索引 1024 处访问的数组 'buf[1024]' 超出范围。 [arrayIndexOutOfBounds]

(错误)在索引 256 处访问的数组 'clientIp[256]' 超出范围。 [arrayIndexOutOfBounds]*

我该如何解决这个问题?

【问题讨论】:

  • 它准确地告诉你问题出在哪里:你的构造函数中的buf[1024] = {}; 正在访问元素 1024,这是超出范围的。卸下 [1024]。更好的是,将所有这些移到构造函数的初始化部分,或者在私有部分中分配默认值。
  • @sweenish 非常感谢您的回答。你能用代码告诉我你对解决方案第一部分的意思吗

标签: c++ arrays constructor initialization indexoutofboundsexception


【解决方案1】:

buf[1024] = {}; 不是你想要的。它将访问buf 的第1024 个元素并默认初始化这个元素,但它超出了范围。

你可能想要什么:

class server : public udp {

public:
    server() : clientLength(), buf(), bytesIn(), count(), clientIp(), portnumber(){
    }

如果可能,您应该始终更喜欢成员初始化列表。

【讨论】:

    猜你喜欢
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多