如何在单独的头文件中的结构中定义char *数组?

时间:2011-11-30 12:11:55

标签: c++ pointers struct header-files

我只是想要了解结构并将事物分成不同的文件。

目前我有一个像这样的Main.cpp文件:

#include <iostream>
    #include "StudentAnswerSheet.hpp"
using std::cout;
using std::endl;

int main(){

    StudentAnswerSheet sheet = {
        "Sally",
        {'a', 'b', 'a', 'd', 'c'}
    };

    cout << sheet.studentName << ":" <<endl;
    for(int i = 0; i <5; i++){
    cout << sheet.studentAnswers[i] << " " ;
    }
    return 0;
}

和一个单独的头文件,其中包含我的struct StudentAnswerSheet数据类型:

#include <string>
using std::string;

struct StudentAnswerSheet{
    string studentName;
    char studentAnswers[5];
};

理想情况下我希望能够拥有一系列最多5个字符来保持学生的答案。我想我可能需要从char更改为char *以获得一定程度的灵活性但是当我尝试实现它时,我收到错误消息“char [0]太多intialiser”并且不确定如何更改工作表初始化

我也不确定如果我切换到char *数组,跟踪我的数组包含多少元素的最佳方法是什么...如果我用cin接受学生答案然后我可以跟踪最多5个答案的数量,但如果我只是想自己初始化答案,就像我现在正在测试我不知道什么是最有效的方法来计算studentAnswers的大小,所以任何建议都将是非常感谢。

感谢您的帮助!

2 个答案:

答案 0 :(得分:4)

由于您似乎可以使用std::string,为什么不使用std::vector<char>而不是使用char[5]或考虑使用char*来提高灵活性?在您的情况下,您只需使用std::string,然后将其中的每个字符解释为学生答案

此外,由于StudentAnswerSheet不是POD,这意味着以下会产生编译错误,除非您使用C ++ 11:

//error in C++98, and C++03; ok in C++11
StudentAnswerSheet sheet = {
    "Sally",
    {'a', 'b', 'a', 'd', 'c'}
};

以下是我要做的事情:

struct StudentAnswerSheet
{
    std::string studentName;
    std::string studentAnswers;

    //constructor helps easy-initialization of object!
    StudentAnswerSheet(const std::string & name, const std::string & answers) 
                : studentName(name), studentAnswers(answers) {}
              //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
};            // it is called member-initialization list

然后将其用作:

StudentAnswerSheet sheet("Sally", "abadc");//easy: thanks to the ctor!

std::cout << sheet.studentName << std::endl;
for(size_t i = 0; i < sheet.studentAnswers.size(); ++i)
{
     std::cout << sheet.studentAnswers[i] << " " ;
}

答案 1 :(得分:0)

我认为你不需要切换,使用char数组是可以的(或者你可以使用std :: vector)。当你使用

char* something[5];

你只是初始化指针数组。当你使用

char something[5]; 

你得到指向数组的指针 - “某事