Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Homework: Making an array using pointers

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. Rewrite the following program to use pointers instead of arrays:

The code is this

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;
}

My solution was this:

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;
}

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!

like image 264
Joey C. Avatar asked Jan 08 '23 01:01

Joey C.


1 Answers

Use

int* salary_pointer = new int[20];

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

delete[] salary_pointer;

instead of delete salary_pointer. Be also careful here:

salary[i] / (i + 1);

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).

like image 96
vsoftco Avatar answered Jan 09 '23 14:01

vsoftco