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.
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!
Use
int* salary_pointer = new int[20];
instead, as you allocate 20 int
s, 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 double
s or a pointer to double
so you don't have this issue anymore).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With