我试图用这种结构创建一个指针数组:
struct No {
int decimal;
char *binary;
char *octal;
char *hexadecimal;
};
我有两个函数来构造数组并打印出数组:
void constructArray (No *Number, int size) {
No **temp = new No *[size];
for (int i = 0; i < size; i++)
{
temp[i]->decimal = rand() % 1000;
temp[i]->binary = "0";
temp[i]->octal = "0";
temp[i]->hexadecimal = "0";
}
}
void printArray (No *Number, int size) {
cout << "Decimal\t" << "Binary\t\t\t" << "Octal\t\t" << "Hexadecimal" << endl;
No **temp = new No *[size];
for (int i = 0; i < size; i++) {
cout << temp[i]->decimal << "\t"
<< temp[i]->binary << "\t\t\t"
<< temp[i]->octal << "\t\t"
<< temp[i]->hexadecimal << endl;
}
}
然后我在主函数中调用它们:
int main() {
No *number;
int size = (rand() % 9) + 1;
constructArray(number,size);
printArray(number,size);
}
该程序已成功编译并运行,但是没有任何输出。我的代码有什么问题?我在这里初始化数组的方式有问题吗?我该如何克服这个问题?预先非常感谢您的帮助。
我认为您的意图需要在您的位置添加一行
for (int i = 0; i < size; i++)
{
temp[i]->decimal = rand() % 1000;
你应该有
for (int i = 0; i < size; i++)
{
temp[i] = new No;
temp[i]->decimal = rand() % 1000;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句