Ran into a wall with Liberty - please help.

Started by
11 comments, last by Northchild 21 years, 7 months ago
Okay, let me try and explain this. I take it the pointer to the free store variable was created in the function. One reason to do this is if you want to return a reference which contains the address of the dynamically created variable. I think you understand that part right? Where an auto variable created inside the function dies when the function exits. Another thing, the only way to allocate memory dynamically is with pointers. Okay, as for scope of a pointer, its just like any other variable, if you create a pointer to lets say int j = 5 inside the main function, then decide to call the blahblah(); function, unless u pass the pointer as an argument it wont be accesible inside blahblah, only main, pointers have regular scope. one reason why you might pass a pointer to a function would be for accessing array''s. Instead of passing the entire array which takes more time depending on the size of it, U can just pass a pointer to the first element or whatever in the array and then use a loop inside the function to access the rest. A static variable persists but is only accessible within its scope, just like an auto variable except that it doesn''t die when the function exits. So if you created a static variable inside a function that''s the only place you can access it. All in all pointers let you allocate memory dynamically and do stuff that you can''t with regular variables. Hope this didn''t just confuse u more.
Advertisement
One more thing I forgot, another reason pointers are handy is lets say... You have an int variable j = 10 in your main function. You call a function blahblah(j); And you pass the VALUE 10, not the actual variable. So if inside the blahblah function you have

blahblah(int z)
{
z = 4; // this wont change the value of j out in the main function. But if you sent a pointer to j as an argument it would, if you changed the syntax of course.

blahblah(int * z)
*z = 4;

And you''re right, the use of pointers and what not are trivial in the dinky little example programs your book probably uses. But as your programs get bigger and you need to do things that are a bit tricky pointers will come in handy. And when you''re not sure how much memory you need to allocate at run time, new comes into play.
Heh, I think we all get stuck in the same part! I''m on like chapter 9-11 which is references and pointers and right now I''m saying "Fuck it dude, this is for nerds." So I''m waiting for "Game programming all In One" from Amazon which covers basic c++ with complete game examples throughout the whole book. I think it''ll make learning c++ more interesting. I''ll dread going back to that cursed c++ in 24 hours...

This topic is closed to new replies.

Advertisement