如何初始化一个指针数组(或者我是否需要这样做)?

时间:2015-08-11 21:31:18

标签: c++ pointers struct

这是我的大学考试,所以不要问我为什么不在C ++中使用高级内容。

这是一款控制台应用。要解决的问题是在定义的结构中编写缺失的函数。这是入学考试的模拟,所以这个问题结构的属性如下:

char* _txtOfQuestion;
char* _answers[10];     //max 10 answers
int _correct;           //location of the correct answer
int _points;            //no. of points

现在,我需要实现此结构的函数Create(),它负责初始化所有结构属性。

我认为参数应该是:

Create(char* text, char* answers[], int posOfCorrect, int points){

    _txtOfQuestion = new char[strlen(text)+1];
    strcpy_s(_txtOfQuestion , strlen(text), text);

    // now this _question[10] attribute seems to be the toughest here 
    // as it happens to be an array
    // how to initialize it here or if init. is not necessary, then
    // how to assign it to this parameter answers, to that it fits?

    // code here....

    _correct = posOfCorrect;
    _points = points;

}

1 个答案:

答案 0 :(得分:0)

你为什么不尝试这样的事情:

for (int i = 0; i < 10; ++i)
{
    if (answers[i] != nullptr)
    {
        _answers[i] = malloc(strlen(answers[i])+1);
        strcpy(_answers[i], answers[i]);
    }
    else
        break;
}

当然你可以省略nullptr检查。 这有用吗?