In Class Questions
[1] When you are referencing a pointer in your program, does the pointer know its a pointer or is it just an integer?
[Thanks to Nikola Whallon for the advice here.]
A pointer stores nothing more than an integer. Depending on the "architecture" that the program is running on, the size of the integer it stores may vary, but this integer is just a spot in memory that has been set aside ("allocated") by your program. The allocation of memory is not something that we have discussed and we likely won't go into great detail given time constraints. If you would like, we can do this in the advanced topics. More details can be found here - http://www.cplusplus.com/doc/tutorial/pointers/.
However, that's still not satisfying I feel, so a bit deeper. It makes you feel that you should be able to treat any integer, lets say you have "x=7;", as pointing to a location (in this case the 7th spot) in memory. Can't I just dereference that location and pick up whatever resides there? The answer is yes and no. This will work as you may expect, and the dereferencing will go to that location and then try to pick up the number of bits that the expected type wants you to take. However, this will only be executed successfully at runtime if the exact location in memory that you are trying to query has been allocated by your program, for whatever reason. You would have to get really lucky for this to happen since there are many memory locations in memory. If you get unlucky, then you will get a "segfault". This is actually a very common runtime error and occurs when you are trying to access an element of memory that you have not previously been given control over. More details can be found here - https://en.wikipedia.org/wiki/Segmentation_fault - along with a few really weird examples.
The most common form of a segfault that you should be able to appreciate now would be if I had this pseudocode:
int x[3] = {1,2,3};
cout<<"Printing off from my array : "<<x[5]<<endl;
In this code, the array has only set aside 3 spaces of int's, so when you try to access the fifth spot, you are looking at a spot in memory that doesn't belong to you.
Good question JIM!
[2] Is it possible to change the type of the pointer so that even though the location has an int, but want to convert it into a double pointer?
This question has to do with something called "casting". The idea of casting has to do with transforming one type of a variable to another type. I won't go into all the details here, but four very good references to read are :
- http://www.cplusplus.com/doc/tutorial/typecasting/
- http://www.cprogramming.com/tutorial/lesson11.html
- http://stackoverflow.com/questions/14373924/typecasting-of-pointers-in-c
- http://stackoverflow.com/questions/17260527/what-are-the-rules-for-casting-pointers-in-c
Please let me know if you would like to cover casting in the additional sessions (that would be held *after* next week)