【问题标题】:Error in Array of struct结构数组中的错误
【发布时间】:2015-01-09 09:49:06
【问题描述】:

我有下一个程序,在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;
}

【问题讨论】:

  • 这不是有效的 C++。类数据成员必须具有完整的类型。
  • 这部分你应该使用std::copy()messag[0].msg[]={ 'a', 't','\r', '\n'};。该语法仅允许用于编译时初始化。
  • 到底是什么问题?
  • 错误是error: excepted primary expression before ']' token

标签: c++ arrays struct


【解决方案1】:

这个结构定义

struct message{

char msg[];

};

错误,因为 msg 的类型不完整。数组的大小未知。

数组也没有赋值运算符。所以你可能不会这样写

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

(此语句在语法上根本不正确)或

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

如果 msg 声明为 std::array&lt;char, 4&gt;,则可以使用最后一条语句。例如

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多