C++ 在C+中初始化构造函数内的字符数组(数组索引超出范围)+;
我试图在构造函数中初始化这两个字符数组。错误出现在字符数组buf和clientip中,其他的都可以。我在下面添加了整个构造函数的代码: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
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]={}构造函数中的code>正在访问元素1024,这超出了范围。卸下[1024]。更好的是,将所有这些移到构造函数的初始化部分,或者在私有部分指定默认值。@sweenish非常感谢您的回答。你能用代码告诉我解决方案的第一部分是什么意思吗