简体   繁体   English

关于动态分配的数组和指针的作业帮助

[英]Homework help regarding dynamically allocated arrays and pointers

Here's my question: 这是我的问题:

Suppose your program contains code to create a dynamically allocated array as follows: 假设您的程序包含用于创建动态分配数组的代码,如下所示:

int * entry;
entry = new int [10];

so that the pointer variable entry is pointing to this dynamically allocated array. 因此指针变量条目指向此动态分配的数组。 Write code to fill this array with ten numbers typed in at the keyboard. 编写代码以在键盘上键入十个数字来填充此数组。

I've gone through the book for two days now and still can't figure this out. 我已经读了两本书了,现在仍然无法弄清楚。

Here's the code I was trying, but it is giving me an error on line 17 that says: No operator matches these operands "<<". 这是我正在尝试的代码,但是它在第17行给了我一个错误,该错误是:没有运算符匹配这些操作数“ <<”。 I've checked the msdn and a couple other websites, but I cant figure this out. 我已经检查了msdn和其他几个网站,但是我无法弄清楚。 Any help would be appreciated. 任何帮助,将不胜感激。

#include <iostream>

using namespace std;

int main()
{
int * entry;
entry = new int [10];
int array_size = 10;
int num;
for(int i = 0; i< array_size; i++)
    entry[i] = i;

for(int i = 0; i < array_size; i++)
{
    cout << "Enter an int into the array: " << endl;
    cin << entry[i] << endl;
}


return 0;
}

You have the wrong direction of the the stream operator: Use cin >> entry[i]; 您对流运算符的方向有误:使用cin >> entry[i]; . A good way of remembering this is thinking of the operator as an arrow: For output, you point the stuff you want to output towards cout , for input, you point the values from cin towards the variable that should store the input. 记住这一点的一种好方法是将运算符视为箭头:对于输出,将要输出的内容指向cout ,对于输入,将cin的值指向应存储输入的变量。

By default, cin >> ... handles whitespace (spaces, tabs, newlines) automatically, so there is no need for the >> endl either. 默认情况下, cin >> ...处理空格(空格,制表符,换行符),因此也不需要>> endl

Finally, the previous loop setting entry[i] = i; 最后,上一个循环设置entry[i] = i; does not do anything useful in your current program as all the entries are overwritten anyways when the users input their values. 在您当前的程序中没有任何用处,因为当用户输入值时,所有条目都会被覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM