作业:使用指针制作数组 [英] Homework: Making an array using pointers

查看:100
本文介绍了作业:使用指针制作数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决一个家庭作业问题.我和其他一些学生很确定我们的老师打错了电话,但也许不是.我已经在这里仔细检查了一些问题,并不能真正找到使用指针创建本质上是数组的方法.说明如下.

I have a homework problem that I'm working out. Me and some other students are pretty sure that our teacher misspoke, but maybe not. I checked through a bit of the questions here already and can't really find a way to use pointers to create what is essentially an array. The instructions read as follows.

  1. 重写以下程序以使用指针而不是数组:

代码是这个

int main()
{
    int salary[20];
    int i;
    for (i = 0; i < 20; i++)
    {
        cout << "Enter Salary: ";
        cin >> salary[i];
    }
    for (i = 0; i < 20; ++i)
        salary[i] = salary[i] + salary[i] / (i + 1);

    return 0;
}

我的解决方法是:

int main()
{
    int* salary_pointer = new int;
    for (int i = 0; i < 20; i++)
    {
        cout << "Enter Salary: ";
        cin >> *(salary_pointer + i);
    }
    for (int i = 0; i < 20; ++i)
    {
        *(salary_pointer + i) = *(salary_pointer + i) + *(salary_pointer + i) / (i + 1);
        cout << *(salary_pointer + i) << endl;
    }
    delete salary_pointer;
    return 0;
}

它一直在大约13号薪水处标记细分错误

It keeps flagging a segmentation fault at about salary number 13

我的主要目的(因为我几乎是肯定的,我的老师把这个错误写下来)是为了更多地了解指针,因此,将不胜感激学习这些令人困惑的事物的所有技巧.谢谢你们!

My main purpose (because I'm almost positive my teacher wrote this down wrong) is to understand more about pointers, so any and all tips and tricks for learning these confusing things would be greatly appreciated. Thank you all!

推荐答案

使用

int* salary_pointer = new int[20];

相反,当您分配20个int时,不只是一个.然后,使用

instead, as you allocate 20 ints, not just one. Then, delete the dynamic array using

delete[] salary_pointer;

而不是delete salary_pointer.这里也要小心:

instead of delete salary_pointer. Be also careful here:

salary[i] / (i + 1);

如果操作数为int,则最终会被截断.如果希望结果作为double,请使用salary[i]/(i + 1.)(在这种情况下,最好将salary做成double的数组或指向double的指针,这样就不再有此问题了).

If the operands are int, then you end up with truncation. Use salary[i]/(i + 1.) in case you want your result as a double (in which case you better make salary an array of doubles or a pointer to double so you don't have this issue anymore).

这篇关于作业:使用指针制作数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆