2015-01-09 66 views
-5

的阵列I具有下一个方案,我有一个问题,当我在struct错误结构

#include <iostream> 

#include <string.h> 


struct message{ 

char msg[]; 

}; 


int main(void) 
{ 

    int i=0; 

    struct message messag[2]; 

    messag[0].msg[]={ 'a', 't','\r', '\n'}; 


    return 0; 
} 
+2

这是无效的C++。类数据成员必须具有完整的类型。 –

+0

你应该为这部分使用['std :: copy()'](http://en.cppreference.com/w/cpp/algorithm/copy):'messag [0] .msg [] = {'a ','t','\ r','\ n'};'。该语法仅适用于编译时初始化。 –

+0

究竟是什么问题? – Codor

回答

1

这种结构定义

struct message{ 

char msg[]; 

}; 

是错误的引入数据,因为MSG的类型不完整。数组的大小是未知的。

此外,数组还没有赋值运算符。所以,你可能不写这样

messag[0].msg[]={ 'a', 't','\r', '\n'}; 

(这种说法只是syntaxically不正确的)或

messag[0].msg={ 'a', 't','\r', '\n'}; 

你可以使用的最后一条语句,如果味精定义应该像std::array<char, 4>。例如,

#include <array> 

//... 

struct message 
{ 
    std::array<char, 4> msg; 
}; 

如果在编译时未知数组大小,那么您需要动态分配数组。例如,你可以使用智能指针std::unique_ptr

这里是一个示范项目

#include <iostream> 
#include <memory> 

struct message 
{ 
    std::unique_ptr<char[]> msg; 
}; 


int main() 
{ 
    message message[2]; 

    message[0].msg.reset(new char[4] { 'a', 't','\r', '\n' }); 

    return 0; 
} 

另一种方法是使用标准的类std::string。例如

#include <string> 

struct message 
{ 
    std::string msg; 
}; 

int main() 
{ 
    message message[2]; 

    message[0].msg = { 'a', 't','\r', '\n' }; 

    return 0; 
}