Jump to content

  • Log In with Google      Sign In   
  • Create Account

Awesome job so far everyone! Please give us your feedback on how our article efforts are going. We still need more finished articles for our May contest theme: Remake the Classics

- - - - -

C++ Workshop - Pointers (Ch. 8)

  • You cannot reply to this topic
88 replies to this topic

#1 JWalsh   Moderators   -  Reputation: 422

Like
0Likes
Like

Posted 17 July 2006 - 09:19 AM

Welcome to the GDNet C++ Workshop – Ch. 8

For a complete introduction to this workshop, please look here. Workshop Overview This workshop is designed to aid people in their journey to learn beginning C++. This workshop is targeted at highly motivated individuals who are interested in learning C++ or who have attempted to learn C++ in the past, but found that without sufficient support and mentoring they were unable to connect all the pieces of this highly complex but powerful programming language. This is a 'guided' self-teaching C++ workshop. Each student is responsible for taking the time to read the material and learn the information. The community and tutors that arise out of this workshop are here for making the learning process run more smoothly, but are not obligated to baby-sit a person's progress. Because everyone will be working from the same textbook (Teach Yourself C++ in 21 days 5th Ed.), students may find it easier to get answers to the specific questions they might have. There is no minimum age requirement, and there is no previous programming experience required. Additionally, this workshop does not attempt to defend C++ as a language, nor does it attempt to demonstrate that C++ is either more or less useful then other programming languages for any particular purpose. People who intend to start a discussion about the differences between C++ and ANY other languages (except as are relevant to a particular discussion), are encouraged to do so elsewhere. This workshop is for educational, not philosophical discussions. Quizzes & Exercises Each week will have quizzes and exercises posted in the weekly threads. Please try and answer them by yourself. As well, please DO NOT post the answers to Quizzes and Exercises within this thread. Once it becomes acceptable to post the answers to quizzes and exercises, an additional thread will be created each week specifically for the purpose of posting quiz answers. If you try with reasonable effort but are unable to answer the questions or complete the exercises, feel free to post a clarification question here on the thread. Tutors, myself, or others will do the best we can to point you in the right direction for finding the answer.

Chapter 8 – Understanding Pointers

Introduction For many, chapter 8 will be the most difficult in the book, and for a few, pointers will continue to be the most challenging aspect of the C++ programming language. The primary reason for this, I suspect, is that while pointers provide direct access to your memory, they are used via a layer of indirection, ie...they are variables which store the address of your data. So in order to access the contents of the data at that place in memory, you must first dereference the pointer. This seems tragically difficult to grasp at first. The power of pointers, however, is extraordinary. It brings with it quick access to heap memory, faster passing of data, and the ability to dynamically allocate memory to store data on the heap. You are now able to propogate the changes made to function arguments by passing the address of the data and you can dynamically reinterpret the contents of your memory. All good things. But as was once said, "great power comes with great responsibility" - in this case, memory cleanup. I suspect there will be many questions this week. So have your thinking caps on. Please remember to use OPINION and WARNING tags whenever applicable. As well, feel free to post your own insights, and review questions or exercises beginning Wednesday or Thursday. Outline of the Reading - Chapter 8
  1. What is a pointer?
  2. Why Would You Use Pointers?
  3. The Stack and The Free Store (Heap)
  4. Another Look at Memory Leaks
  5. Creating Object on The Free Store
  6. Deleting Object From The Free Store
  7. Accessing Data Members
  8. Creating Member Data on The Free Store
  9. The this Pointer
  10. Stray, Wild, or Dangling Pointers
  11. Using const Pointers

Good Luck!

[Edited by - jwalsh on May 30, 2007 12:59:25 PM]
Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints

Ad:

#2 Dave   Members   -  Reputation: 1418

Like
0Likes
Like

Posted 17 July 2006 - 09:24 AM

3. The Stack and The Free Store (Heap)

Note that the heap and the freestore are NOT the same thing.

Dave

#3 simesf   Members   -  Reputation: 122

Like
0Likes
Like

Posted 18 July 2006 - 03:50 AM

Quote:
Original post by Dave
3. The Stack and The Free Store (Heap)

Note that the heap and the freestore are NOT the same thing.

Dave



Could you elaborate on that a bit, Dave?


#4 Dave   Members   -  Reputation: 1418

Like
0Likes
Like

Posted 18 July 2006 - 03:57 AM

Hey

The Free Store is where memory is allocated and deallocated using new and delete.

The Heap is where memory is allocated and deallocated using malloc() and free().

The two arn't interchangable, meaning that if something is allocated using malloc() then it can't be cleaned up with delete and that something can't be new'd and then free()'d.

Hope that helps,

Dave

#5 playstation   Members   -  Reputation: 146

Like
0Likes
Like

Posted 18 July 2006 - 06:43 AM

Hi, I have a doubt while using pointers if we want to access int i variable then we also give ptr as int type. why? Is that the only way. what is the reason behind it[rolleyes].

I saw in a C book a prog to write length of string using arrays and we can also do using pointers. Can someone tell me how to write a prog.

If I give input: abc and check if abc then print alphabets in order. I tried but string does not work only single character is working for me. How can I do this?[help] pointers are used if so how[totally].

#6 simesf   Members   -  Reputation: 122

Like
0Likes
Like

Posted 18 July 2006 - 09:17 AM

Quote:
Original post by Dave
Hey

The Free Store is where memory is allocated and deallocated using new and delete.

The Heap is where memory is allocated and deallocated using malloc() and free().

The two arn't interchangable, meaning that if something is allocated using malloc() then it can't be cleaned up with delete and that something can't be new'd and then free()'d.

Hope that helps,

Dave


Thanks Dave. While I don't know about malloc & free yet, having a workable distinction stops me from fretting about it.


#7 Dave   Members   -  Reputation: 1418

Like
0Likes
Like

Posted 18 July 2006 - 09:24 AM

Quote:

Hi, I have a doubt while using pointers if we want to access int i variable then we also give ptr as int type. why? Is that the only way. what is the reason behind it[rolleyes].


This is one of, if not the most important aspects of C++, type safety. There is no other reason to have the pointer as a type* other than to preserve this type independance and safety. If every pointer was of the same type, how would you know what type it was pointing to?

Quote:

I saw in a C book a prog to write length of string using arrays and we can also do using pointers. Can someone tell me how to write a prog.


I'm not entirely sure what you mean, could you reprase please and post any code you have already written up?

Quote:

If I give input: abc and check if abc then print alphabets in order. I tried but string does not work only single character is working for me. How can I do this?[help] pointers are used if so how[totally].


Could you paste your code please?

Dave

#8 Dave   Members   -  Reputation: 1418

Like
0Likes
Like

Posted 18 July 2006 - 09:27 AM

Quote:
Original post by simesf
Quote:
Original post by Dave
Hey

The Free Store is where memory is allocated and deallocated using new and delete.

The Heap is where memory is allocated and deallocated using malloc() and free().

The two arn't interchangable, meaning that if something is allocated using malloc() then it can't be cleaned up with delete and that something can't be new'd and then free()'d.

Hope that helps,

Dave


Thanks Dave. While I don't know about malloc & free yet, having a workable distinction stops me from fretting about it.


malloc() and free() are functions that are used for dynamic memory allocation in C.

#9 rip-off   Moderators   -  Reputation: 5033

Like
0Likes
Like

Posted 18 July 2006 - 09:39 AM

Quote:
Original post by simesf
Quote:
Original post by Dave
Hey

The Free Store is where memory is allocated and deallocated using new and delete.

The Heap is where memory is allocated and deallocated using malloc() and free().

The two arn't interchangable, meaning that if something is allocated using malloc() then it can't be cleaned up with delete and that something can't be new'd and then free()'d.

Hope that helps,

Dave


Thanks Dave. While I don't know about malloc & free yet, having a workable distinction stops me from fretting about it.


In c++, you use the keywords "new" and "delete" (and new[], delete[] ) to dynamically allocate memory.

c++ was built on c, which had 2 functions which did almost the same thing, malloc() and free(). malloc() takes a integral parameter which indicates the number of bytes to be allocated.

The most important differences between them though are this:

0) they are not interchangeable. do not try to delete what was malloc()ed, and do not try to free() what was newed. Beware, with some compilers code like this will work, but it is non-standard and unsupported.

1) malloc will not call constructors, and free will not call destructors.

2) Unlike new, malloc will return NULL, or 0, if it cannot make the allocation. new will throw an exception ( I dont know if you have covered these yet, but if you haven't yet I'll just say that your program will end if you can no longer allocate. With exceptions you also have the opportunity of handling such errors gracefully, should you be able to )


// c++ code:
int *i = new int;
// use *i
delete i;


// c code:
int *i = malloc( sizeof(int) );
if( i == NULL ) // or i == 0
{
// handle the "couldnt allocate" error.
}
else
{
// use *i
}
free(i);



All in all it is much easier to use new and delete.

I hope this shows you what you wanted to know.


#10 simesf   Members   -  Reputation: 122

Like
0Likes
Like

Posted 18 July 2006 - 08:22 PM

That makes it crystal clear & I'll be jotting this in my notebook so thankyou muchly Rip Off.

#11 simesf   Members   -  Reputation: 122

Like
0Likes
Like

Posted 18 July 2006 - 08:37 PM

I think I'm fairly comfortable with the idea of pointers now, although I wish they were called something else - '... and the pointer points to another pointer pointing at the pointed at value...' - if I can barely get my tongue round this just imagine what it's doing to my brain. But it's basically looking at the address on the letter instead of the Dear John letter inside. If she's not a constant woman she could change her mind and put another letter in the envelope.

But the 'this' pointer stumps me. I'm sure it will be covered in a later section as to why you would use it, and in preference to a regular pointer but it's hard to take things on faith when you're as old as me. For pointers in general it would be great to hear about real world uses for them. I imagine one example would be if you wanted a new footsoldier to be created in an RTS you would use a pointer to the free store to create a new object while the program was running. Are there any other examples for using pointers?

#12 RinusMaximus   Members   -  Reputation: 122

Like
0Likes
Like

Posted 18 July 2006 - 08:39 PM

Moved to the week 6 topic.

[Edited by - RinusMaximus on July 19, 2006 4:39:55 AM]

#13 Emmanuel Deloget   Members   -  Reputation: 1354

Like
0Likes
Like

Posted 18 July 2006 - 09:22 PM

Quote:
Original post by RinusMaximus
I have a question which is not related to this Chapter, but to the ColorMenu exercise, but since this is the most active topic I'll post it here.

Since it is easy to spot new posts on an older topic, you should post your question in its correct chapter thread. It will prevent thread hijacking and long discussions about subjects that are not related to the current chapter, and it will also allow new reader to spot the answer to the same exact question if they need it. I'm posting my answer in the correct thread.

Regards,

#14 Telastyn   Members   -  Reputation: 3328

Like
0Likes
Like

Posted 19 July 2006 - 03:49 AM

Forewarning: I am not a tutor.


For pointers, it's sometimes useful when starting out to think of them like web links.

A link (pointer) by itself is pretty useless, but if you follow the link (dereference the pointer) you'll hopefully get to the website (data). Similarly, the usage and problems follow a similar pattern.

Would you copy the entire website to send it to a friend? No, you'd just send your friend a link. Why? Well, sending the entire website contents is a lot of work compared to a URL. Pointers too are far smaller than large data structures. More importantly though, sending your friend the link means they'll see the same site. If you send them a copy, they won't notice any changes or updates to the site itself. Anyone with a link can visit the site whenever they like to see updates. Anyone with a pointer can dereference it to see the data it points to, and all will see any changes made.

So what happens if the webserver is down, or you mis-type a link? Right, problems. Pointers have the same problems (though their problems are often more serious!). If the data the pointers point at gets deleted, it's akin to the web server being down. Links to the site still exist, but following them doesn't work. Pointers to 'garbage' (low values like 0x00000000, or high values such as 0xcdcdcdcd) are like mis-typed links and most often caused by not initializing them properly. Like links, they're fine as long as you don't follow (dereference) them. Most often they won't lead anywhere and break (crash your program). Sometimes they will point to something, but not what you wanted, leading to weird and hard to find bugs.

#15 Zahlman   Moderators   -  Reputation: 1666

Like
0Likes
Like

Posted 19 July 2006 - 07:49 AM

Quote:
Original post by simesf
But the 'this' pointer stumps me.


Member functions are different from ordinary functions. They are "bound" to instances of the object, and implicitly take their own instance as a parameter. The 'this' pointer is simply a pointer that automatically points at "the current object".


class Foo {
int bar;
public:
void wibble() {
bar = 1; // the usual way
this->bar = 1; // making use of the 'this pointer'
}
};

int main() {
Foo x, y;
x.wibble(); // <-- 'this' points to x
y.wibble(); // <-- 'this' points to y
}


#16 boolai   Members   -  Reputation: 100

Like
0Likes
Like

Posted 19 July 2006 - 08:08 AM

What is the best way to return a pointer in a function?
Ex:
DataType *m_pPointer;

//This
DataType* Getpointer(void);

//Or this
DataType& Getpointer(void);

ok I know the the "&" returns the address of the pointer.
But returning with "*" symbol just creates a new pointer that will create a dangling pointer?

#17 Zahlman   Moderators   -  Reputation: 1666

Like
0Likes
Like

Posted 19 July 2006 - 09:59 AM

Quote:
Original post by boolai
What is the best way to return a pointer in a function?
Ex:
DataType *m_pPointer;

//This
DataType* Getpointer(void);

//Or this
DataType& Getpointer(void);

ok I know the the "&" returns the address of the pointer.
But returning with "*" symbol just creates a new pointer that will create a dangling pointer?


[OPINION]0) Don't write (void) for function prototypes. Write (). This is technically an opinion, but it's an opinion that the inventors of C and of C++ happen to share. :)[/OPINION]

1) Nothing in the function prototype actually returns anything; it simply says what kind of thing you will return.

2) "DataType&" means you will return a reference to the thing. References and pointers are different things. You should read this.

3) "DataType*" means you will return a pointer to the thing. Whether that pointer is valid, or what it actually points to, depends on (the correctness of) the implementation code.

4) If the member is itself a pointer, then you have to be clear about whether you're returning a pointer or reference *to that pointer*, or *to the thing which is pointed at*. Note that by returning a reference to a pointed-at thing, you are effectively promising that the pointer is not NULL, because the reference must refer to a valid object (see the link).

#18 Emmanuel Deloget   Members   -  Reputation: 1354

Like
0Likes
Like

Posted 19 July 2006 - 10:39 AM

Quote:
Original post by boolai
What is the best way to return a pointer in a function?
Ex:
DataType *m_pPointer;

//This
DataType* Getpointer(void);

//Or this
DataType& Getpointer(void);

<see below>
But returning with "*" symbol just creates a new pointer that will create a dangling pointer?


The later don't return a pointer, it returns a reference. Only the first one returns a pointer. Both function, however, return their result by value, meaning that the first one returns a copy of a pointer and the second one returns a copy of a reference. Nothing is created at this point.

Lets do something simple:

class A
{
public:
// we simply return this
A* getThisPtr() { return this; }

// we have to dereference this to be able to return a reference
A& getThisRef() { return *this; }

// this method returns a <i>copy</i> of the object pointed by "this"
// again, we need to dereference this
A getThisCopy() { return *this; }
};

int main()
{
A a;

// ptr points to a
// changing the content of what ptr reference will change a as well
A *ptr = a.getThisPtr();

// ref references a (changing the content of ref will change a as well)
A& ref = a.getThisRef();

// copy is a new object - a copy of a
// changing copy will not affect a
A copy = a.getThisCopy();
}



Quote:
Original post by boolai
ok I know the the "&" returns the address of the pointer.


Take care: the & operator is used in two different flavor: if it is used in conjunction with a type (as in int& someVar = someOtherVar;), it defines a reference (I guess you'll see them in a few days, so I'm not going to boggle your mind with this right now). If it is used in conjunction with a variable (as in int* ptr = &someVar), it is the address-of operator which returns a pointer to the variable.
In your case, "&" don't return anything - you are in the first case, and it is really a type modifier (as "*").

While I'm at it, take care of a well known problem: you can't return the address of something which lies on the stack (I believe that this issue is already addressed in the book).

Regards,

#19 Oluseyi   Staff Emeritus   -  Reputation: 1668

Like
0Likes
Like

Posted 19 July 2006 - 11:25 AM

Quote:
Original post by Emmanuel Deloget
Take care: the & operator is used in two different flavor: ...

Three. You forgot bitwise-AND.

#20 boolai   Members   -  Reputation: 100

Like
0Likes
Like

Posted 19 July 2006 - 01:38 PM

Hey thanks for the info. Just another question.
Now let take the last function

DataType* GetPointer(DataType* p_pointer)
{
//create a temp pointer
DataType* TempPointer = new DataType;
//copy
m_pPointer = TempPointer;

//Do we need to delete TempPointer or will the function
//Do it for us?
delete TempPointer;

return m_pPpointer;
}//end of function

I know that c++ will delete the parameter first then any local variables and then do the return; Do we still need to delete the TempPointer from memory?





PARTNERS