Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHong Tan
2,567 PointsWhat keeps track the size of the pointer?
What keeps track the size of the pointer? Does the compiler / runtime know this because of the pointer datatype? I supposed it would be easy for generic datatypes, since those are defined but what about custom datatypes?
2 Answers
Tommy Choe
38,156 PointsHey Hong, I found a heated debate that you can sift through to see if you can find the answer you're looking for. http://stackoverflow.com/questions/3520059/does-the-size-of-pointers-vary-in-c
From what I know, size of pointers are all the same size with no regard to what type they are pointing to. Pointers are simply pointing to a specific memory address. However, I guess conceptually, the size of pointers could vary depending on the platform (i.e 64-bit, 32-bit, etc.).
Let me know if you find what you're looking for.
Hong Tan
2,567 PointsThis is all very helpful. Thanks!
nolantenpas
15,573 Pointsnolantenpas
15,573 PointsI agree with Tommy, but figured I'd add a couple things:
If you are using gcc as a compiler, you can use the -m32 flag to create a 32bit executables, or target 32bit architectures. This makes all pointers 4 bytes, instead of 8 bytes.
Also, keep in mind that if you have a pointer to a character and add 1 to it, the resulting address of the pointer is one byte further in memory.
If you have a pointer to an integer and add 1 to it, the resulting address of the pointer is sizeof(int) bytes or (usually) 4 bytes further in memory.
Also, let's say you have a pointer to a struct with 4 different character members. If you add 1 to this pointer, it will add 4*sizeof(char) or 4 bytes to the pointer address.
Sometimes if I do pointer arithmetic, I will cast the pointer to a char pointer in order to enforce single byte addition.