Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C+中初始化构造函数内的字符数组(数组索引超出范围)+;_C++_Arrays_Constructor_Initialization_Indexoutofboundsexception - Fatal编程技术网

C++ 在C+中初始化构造函数内的字符数组(数组索引超出范围)+;

C++ 在C+中初始化构造函数内的字符数组(数组索引超出范围)+;,c++,arrays,constructor,initialization,indexoutofboundsexception,C++,Arrays,Constructor,Initialization,Indexoutofboundsexception,我试图在构造函数中初始化这两个字符数组。错误出现在字符数组buf和clientip中,其他的都可以。我在下面添加了整个构造函数的代码: class server : public udp { public: server() { clientLength = 0; buf[1024] = {}; bytesIn = 0; count = 0; clientIp[256] = {}; por

我试图在构造函数中初始化这两个字符数组。错误出现在字符数组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;
警告是:

*(错误)在索引1024处访问了数组“buf[1024]”,超出了范围。[阵列索引边界外]

(错误)在索引256处访问了数组“clientIp[256]”,超出了范围。[阵列索引边界外]*


如何解决这个问题?

buf[1024]={}不符合您的要求。它将访问
buf
的第1024个元素,并默认仅初始化该元素,但它超出了范围

您可能想要的:

class server : public udp {

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

如果可能的话,您应该总是选择成员初始化列表。

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