如何初始化指针数组(或者我需要这样做)? 这是为了我的大学考试,所以不要问我为什么不在C++中使用高级的东西。

如何初始化指针数组(或者我需要这样做)? 这是为了我的大学考试,所以不要问我为什么不在C++中使用高级的东西。,c++,pointers,struct,C++,Pointers,Struct,这是一个控制台应用程序。要解决的问题是在定义的结构中写入缺少的函数。这是模拟入学考试,因此有一个问题结构,其属性如下: char* _txtOfQuestion; char* _answers[10]; //max 10 answers int _correct; //location of the correct answer int _points; //no. of points 现在,我需要实现这个结构的函数Create(),它负责初始

这是一个控制台应用程序。要解决的问题是在定义的结构中写入缺少的函数。这是模拟入学考试,因此有一个问题结构,其属性如下:

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;

}

你为什么不试试这样的东西:

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;
}
for(int i=0;i<10;++i)
{
如果(回答[i]!=nullptr)
{
_答案[i]=malloc(strlen(答案[i])+1);
strcpy(_answers[i],answers[i]);
}
其他的
打破
}
当然,您可以省略nullptr检查。
这有用吗?

迭代、分配、复制。如果你不想要C++,为什么要加标签?是关于C还是C++的考试?它们不是同一种语言,这个代码是C,不是C++。你不使用的特征不是高级的东西,它们是最基本的C++,你可以学习,比C内存管理垃圾要简单得多。请不要在2种语言的差异之间开始一个无用的愚蠢的讨论,在某些情况下,它们是相似的,但不一样,好吧,我们已经理解了所有这些看起来像C++。code>new不会在
C
中编译。是的,有人已经提到了迭代,我想这就是我需要的。我将在以后继续编码,并接受这个答案,如果它工作。非常感谢。最好给
\u answers[i]
一个所有10个索引的值,即使
answers[i]
很短。或者抛出一个异常:-),但你是对的-这就是我在写nullptr检查时的意思复制指针值而不是字符串本身不会产生任何效果。使用
malloc
strcpy
。我得投反对票,对不起,当然。我修好了,也许现在更好了