Homework: Creating an Array Using Pointers

I have a home problem I'm working on. I and some other students are quite sure that our teacher made a reservation, but maybe not. I already checked a few questions here and can't find a way to use pointers to create what is essentially an array. Instructions are read as follows.

  1. Rewrite the following program to use pointers instead of arrays:

Code is

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 as follows:

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

He continues to report a segmentation error of approximately salary number 13

( , ) , , . !

+4
4

int* salary_pointer = new int[20];

, 20 int s, . ,

delete[] salary_pointer;

delete salary_pointer. :

salary[i] / (i + 1);

int, . salary[i]/(i + 1.), , double ( salary double double, ).

+9

. .

? ? ?

seg, , .

, , .

, STL , .

+1

?

. SINGLE. , for, , , , , , , STRESS, . undefined .

, . , , "20". - const int MAX_SALARIES = 20. , TONS .

0

int* salary_pointer = new int;

int.

And since the division operation is used, it is better to use a type floatinstead of an intarray.

I would suggest the following solution. It uses only pointers.

#include <iostream>

int main()
{
    const size_t N = 20;
    float *salary = new float[N];
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
    for ( float *p = salary; p != salary + N; ++p )
    {
        std::cout << "Enter Salary: ";
        std::cin >> *p;
    }

    for ( float *p = salary; p != salary + N; ++p )
    {
        *p += *p / ( p - salary + 1 );
    }

    delete [] salary;
    ^^^^^^^^^^^^^^^^
    return 0;
}
-1
source

Source: https://habr.com/ru/post/1618648/


All Articles