Finding the code error

Hey guys. I bought the C++ How to Program (Early Objects Version) 9th Edition and I am on Chapter 8 on pointers. I have come across the questions in the self review that I can't seem to figure out. In this I have to find the programming error. Any help would be really appreciated. I am trying to learn on my own and the internet probably has stuff, I just cannot find it.

Here is what I think so far, and I would like to be told if I am wrong.

#1 Void should be changed to something like short or int
#2 the line short *numPtr, result; the *numPtr should be set to something like nullptr or some sort of number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <array>
#include <cmath>
#include <fstream>


using namespace std;



int main()
{

	
	short *numPtr = 0, result;
	short *genericPtr = numPtr;
	result = *genericPtr + 7;

	cout << result;

return 0;
}
Last edited on
Line 16: genericPtr should be a short *

Line 15: numPtr is uninitialized (it doesn't point to anything).

Line 17,19: result is going to be meaningless since genericPtr was set to an uninitialized pointer.
@AbstractionAnon

I updated the code and tried running it, it goess to cmd, but crashes. If I try making *numPtr another number like 5 it comes as an error as well. I tried those 3 things you suggested prior as well, but still nothing.
Line 15: What do you think numPtr points to?

You set it to 0, which means memory location 0. On most systems location 0 is an invalid memory reference and guaranteed to cause your program to crash.

Line 16-17: Since numPtr is now 0, genericPtr is also now 0. Ditto regarding program crash.

Line 17: result is still meaningless since genericPtr is invalid.


> In this I have to find the programming error.
It would be nice to see the original exercise and not just your failed solution.


> Here is what I think so far
You jump to action too early.
First, ¿what's the purpose of the program?
Second, ¿is there an error?
Then you'll analyse the error, found possible causes and solutions.
Topic archived. No new replies allowed.