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 trialdovlavi
358 PointsPointers and memory
when using pointy = α am I not just getting the location in memory where alpha is stored? and if thats the case, why does it print whatever 'alpha' is currently assigned to and not the actual address space?
Can someone please elaborate on pointers - I don't think the video was very clear.
Please help :)
Thanks!
3 Answers
Stone Preston
42,016 Pointsyes, using the & operator gets the memory address of the variable. so
char alpha = 'a'
char *pointy = α
would make pointy "point" to the memory address of alpha. if you want to print the value of pointy (not the address) you would have to dereference it using the * operator:
//pointy value: a would be printed
printf("pointy value: %c", *pointy);
if you wanted to print the memory address that pointy points to, you would need to use the %p format specifier and just reference the pointer name, without a *
//prints the address pointy points to
printf("pointy value: %p", pointy);
if you declared another pointer variable and wanted to point it at the same address as pointy, you would use
//anotherPointer points to the same address as pointy
char *anotherPointer = pointy;
since pointy by itself (without the * operator) is a memory address, anotherPointer now points to the same address as your pointy pointer. If you wanted to assign the value that pointy points to to a variable, you would have to dereference it
//since the value at the memory address pointy points to is 'a', someChar now has a value of 'a'
char someChar = *pointy;
TLDR; *pointy
references the value thats at the memory address the pointer points to, pointy
references the memory address that pointy points to, &alpha
references the memory address of the variable alpha.
agreatdaytocode
24,757 PointsI vote that Stone does the next IOS treehouse video. Great answer!
dovlavi
358 PointsAgreed!!
Luis Kentzler
13,869 PointsAgreed!
dovlavi
358 PointsNow I get it! Thanks!
Much better! Dont think the video really explained that. :(