Jump to content
Sign in to follow this  
chris330

C++ pointer referencing

Recommended Posts

I'm learning C++ and I'm having trouble understanding the concept of referencing when applied to pointer variables.

As I understand it, pointer variables contain an address not a variable. You can access the data stored at that address by placing a * symbol before the variable.

I also gather that you can pass the address of a regular variable into a pointer variable using the & symbol like so:

p_variable = &myvariable

This all makes sense but for the following thing. When talking about overloading the output operator << the book's author does something rather unusual:

ostream& << operator (ostream& str_out, struct car& d)

The variable 'd' is to have the same data type as the user defined structure called 'car'. What confuses me is that earlier in the book the author defines function headers in exactly the same way without using the & symbol.

He then goes on to state that the reason he has used the & symbol here is to make the variable 'd' a reference to a pointer variable which enables one to treat a pointer variable like an ordinary variable huh.gif

So he is stating that 'struct car' is a pointer variable or 'd' is a pointer variable. Neither of which appears to be true to me because 'struct car' is a user defined data type and not a pointer variable. Also 'd' is an internal function variable not something which holds a memory address.

He then goes on to state that when defining an array variable in the function header he does not need the & symbol because an array variable is already a pointer variable! So doesn't that mean that in the original case the internal function variable 'd' was turned into a pointer variable using the & symbol huh.gif Wouldn't we normally just use the following code to do that:

int* d

And also if you look wouldn't that mean he was defining a pointer variable of type structure! Surely pointer variables can only be of type integer!

Please someone tell me what the hell is going on help.gif

Share this post


Link to post
Share on other sites
Quote[/b] ]Surely pointer variables can only be of type integer!

Nope, you can point to any data type. smile_o.gif

Quote[/b] ]hen defining an array variable in the function header he does not need the & symbol because an array variable is already a pointer variable

Yeah, that's true! For funnage, try the following:

1) pass 2 variables into a function; the variables should be passed to variables of the same name

2) Manipulate, in the function, the variables and output their values

3) Return to main, and output the originally passed values - they will not have changed as per 2)

Why? Because you copied the content of the variable into the function.

Now try the same with an array, i.e.:

1) pass an array to a function

2) Modify some array elements in that array, output their values

3) Return to your main, and display the original array - the values have changed!

The array element, e.g. <table border="0" align="center" width="95%" cellpadding="0" cellspacing="0"><tr><td>Code Sample </td></tr><tr><td id="CODE">array[x], is just a pointer, as an array is a block of memory reserved for that array, but you need the subscript to "point" to the required location wink_o.gif

Quote[/b] ]Also 'd' is an internal function variable not something which holds a memory address

All variables have a memory address - otherwise, the data stored in them could not be accessed! wink_o.gif You use the plain variable to access the data, but the pointer to access the address.

Quote[/b] ]He then goes on to state that the reason he has used the & symbol here is to make the variable 'd' a reference to a pointer variable which enables one to treat a pointer variable like an ordinary variable

Yeah, so he creates a variable that, as data, contains an address, I think. It is well possible to do that smile_o.gif

Quote[/b] ]ostream& << operator (ostream& str_out, struct car& d)

NO idea about this though crazy_o.gif Never done C++! C is almost the same though.

I hope this helped. I know it can be confusing, but just keep playing, use printf a lot to see what is happening to the variables and the data they contain, then you will slowly get a "feel" for things as you gain experience thumbs-up.gif

Share this post


Link to post
Share on other sites
I'm learning C++ and I'm having trouble understanding the concept of referencing when applied to pointer variables.

As I understand it, pointer variables contain an address not a variable. You can access the data stored at that address by placing a * symbol before the variable.

I also gather that you can pass the address of a regular variable into a pointer variable using the & symbol like so:

p_variable = &myvariable

This all makes sense but for the following thing. When talking about overloading the output operator << the book's author does something rather unusual:

ostream& << operator (ostream& str_out, struct car& d)

The variable 'd' is to have the same data type as the user defined structure called 'car'. What confuses me is that earlier in the book the author defines function headers in exactly the same way without using the & symbol.

He then goes on to state that the reason he has used the & symbol here is to make the variable 'd' a reference to a pointer variable which enables one to treat a pointer variable like an ordinary variable huh.gif

So he is stating that 'struct car' is a pointer variable or 'd' is a pointer variable. Neither of which appears to be true to me because 'struct car' is a user defined data type and not a pointer variable. Also 'd' is an internal function variable not something which holds a memory address.

He then goes on to state that when defining an array variable in the function header he does not need the & symbol because an array variable is already a pointer variable! So doesn't that mean that in the original case the internal function variable 'd' was turned into a pointer variable using the & symbol huh.gif Wouldn't we normally just use the following code to do that:

int* d

And also if you look wouldn't that mean he was defining a pointer variable of type structure! Surely pointer variables can only be of type integer!

Please someone tell me what the hell is going on help.gif

Haven't learned C++ but... It appeers valid to me, that the new variable called d is simply being defined as the type 'struct car' which is a user-defined structure. If I remembers correctly - and if it's similar to other languages, the '&' simply means you are writing to a variable.

We now have a simple variable of the type 'car' with the memoryadress information (pointer-information).

But don't listen to me, cause I really don't know C++... But this is the only way I can see it's true if the book is right.

Cheers...

Share this post


Link to post
Share on other sites

I leran PASCAL,

A dead computer language . .I think it was made whem my dad was born :-P

Share this post


Link to post
Share on other sites

Me too... But it's very fast for simple things, that is why you can use it in digital circuits when programming you chips biggrin_o.gif

Share this post


Link to post
Share on other sites
ostream& << operator (ostream& str_out, struct car& d)

hmm ok I do not get this fully aswell but you gotta make a difference with the & (aswell as the *) signs.

The difference is as follows:

&x (this will return the memory address of the variable x)

int& rx; (this a declaration and here the sign doesn't return the adress but it defines a variable wich is of type "reference on int" - it can also be written as "int &rx;" but I like to use the sign after the type in this case to make a distinction.

so in your example d is a variable that is of type "reference on car", in other words, d will be essentially the same as what you pass to it (not another variable with the same content) plus d does not hold an adress. [EDIT]

Therefore whatever you do with d will change the value of what has been passed to d as a parameter.[/EDIT]

I have no idea if that helps, but I am learning C++ at the moment aswell wink_o.gif

Share this post


Link to post
Share on other sites

Lol only been gone an hour and already all these replies! That's just what I wanted as I'll certainly get to the bottom of this with other people's help, so thanks to all whom have repied so far especially those who wrote lengthly replies smile_o.gif

It appears there is no problem in life that cannot be solved on this forum. If anyone knows who to avoid excessive flatulence when including lots of fibre in your diet I'll be really impressed wink_o.gif

I'll print this thread off now and have a good read through it. I'll be back in touch when I've made some conclusions thumbs-up.gif

Time passes.....

*Later that day*

Had another think and I understand the point (no pun intended) of how a function which is manipulating a pointer variable will alter external values also as it is directly accessing a memory address. I also understand the other points made too, like the one where 'd' is holding a value with no individual address. However,

When the author states that the array variable 'd[4]' needs no conversion because it is a pointer variable like so:

ostream& << operator (ostream& str_out, struct car d[4])

isn't he basically saying that if an array variable needs no conversion because it is already a pointer, then the ordinary variable 'd' needs converting to a pointer for the function to be able to use it?

So he isn't he stating that the function would normally expect to find a pointer variable declared in the function header?

This is most definitely not the case in other functions such as this one for example which accepts an integer input and doubles it and returns a integer output. The function is called 'increase':

Function description

int increase(int x)

{ x = x * 2

  return(x)

};

In use

int myvariable = 2

int newvariable

newvariable = increase(myvariable)

//(newvariable now equals 4)

That's a typical and common example of the type used throughout the book. No reference to pointer variables mentioned or anything like that. Why has he not just kept the same convention for the operator overload function? Is it perhaps something to do with the operator overload function being of a specific and unusual type?

Just to clear things up by referencing to a pointer variable am I referencing to the data held at the address contained in the pointer variable or the address itself?

Hmm, still a long way to go before I understand this one. So far the book has been superb but this part of it is shockingly under-explained.

Share this post


Link to post
Share on other sites
ostream& << operator (ostream& str_out, struct car d[4])

Just a question, what book is this? And why the hell is he using "struct car", instead of just "car"?

In C you need to do "struct car", or you make a typedef, so you don't need the struct namespace.

But this is C++...

Quote[/b] ]isn't he basically saying that if an array variable needs no conversion because it is already a pointer, then the ordinary variable 'd' needs converting to a pointer for the function to be able to use it?

In C and C++ an array is a pointer.

Quote[/b] ]

This is most definitely not the case in other functions such as this one for example which accepts an integer input and doubles it and returns a integer output. The function is called 'increase':

Function description

int increase(int x)

{ x = x * 2

return(x)

};

In use

int myvariable = 2

int newvariable

newvariable = increase(myvariable)

//(newvariable now equals 4)

That example doesn't make sense; or the function has the wrong name.

You should call this function getDoubleOf or something like that. If you call a function "increase" I'd expect, that this function actually increases the parameter.

Something like this:

<table border="0" align="center" width="95%" cellpadding="0" cellspacing="0"><tr><td>Code Sample </td></tr><tr><td id="CODE">

void increase( int& x )

{

x++;

}

Quote[/b] ]

Just to clear things up by referencing to a pointer variable am I referencing to the data held at the address contained in the pointer variable or the address itself?

Do you mean this:

ostream& operator<< ( ostream& str_out, car* & d )

?

Here "d" is a reference to a pointer to a car. So every change you make to d is a change to the pointer, not to the data.

Share this post


Link to post
Share on other sites

Thanks for the reply. I used the name increase because I couldn't think of anything else at the time. It's just to demonstrate the fact that the author of the book has only just introduced all this & stuff in the function header's at page 190 in the book and he's been talking about functions for the last 100+ pages!

It's totally thrown me. The book is called

"The Idiot's Guide to C++"

Quite an apt name given the trouble I'm having with this part of it. It's been great up to here. God knows why he is using struct car instead of car I really don't know, but that is what he's doing.

To give a better example here goes:

Function Prototype

int getdouble(int x)

Function Description

int getdouble(int x)

{x = x * 2;

return(x);

}

In use

int myvariable = 2

int newvariable

newvariable = getdouble(myvariable)

I hope that makes more sense. Just an example to show you that he hasn't been using the & symbol in any other functions in the book he's just suddenly started using it now when talking about overloading the operator wink_o.gif

I've found a good page on google which I'm going to have a look at now. If you want I can post a couple of scanned images in of the book pages in question. It might help make things clearer thumbs-up.gif

Share this post


Link to post
Share on other sites

"The Idiot's Guide to C++"

biggrin_o.gif

Ok, References (the & stuff) are pretty easy: They are just some kind of alias for the parameter. You can avoid the ugly pointer syntax with them.

Let's say we have the struct car:

<table border="0" align="center" width="95%" cellpadding="0" cellspacing="0"><tr><td>Code Sample </td></tr><tr><td id="CODE">

struct car

{

int foo;

int bar;

};

Now you make a function, that does changes to the parameter, you pass in. There are two possibilities: By reference and by pointer.

<table border="0" align="center" width="95%" cellpadding="0" cellspacing="0"><tr><td>Code Sample </td></tr><tr><td id="CODE">

#include <iostream>

using namespace std;

void makeFoo( car* c )

{

c->foo = 0;

}

void makeFoo2( car& c )

{

c.foo = 0;

}

int main()

{

car c;

c.foo = 5;

cout << c.foo << endl; // prints 5

makeFoo( &c );

cout << c.foo << endl; // prints 0

c.foo = 5;

cout << c.foo << endl; // prints 5

makeFoo2( c );

cout << c.foo << endl; // prints 0

return 0;

}

As for operator overloading: Normally you implement them through passing a reference or a "constant reference" (const foo&).

Passing by reference has a big advantage over passing by value. You just pass the address to the data (on 32bit systems it's 4 byte, on 64bit systems it's 8byte) instead of the data itself (which can be a lot for complex structs/classes).

(Of course the same applies to pointers, but the syntax is uglier)

Hope that helps a bit...

Share this post


Link to post
Share on other sites
I leran PASCAL,

A dead computer language . .I think it was made whem my dad was born :-P

Nop .... Delphi is still alive and well ..... cuz its my prefered programming package.

Share this post


Link to post
Share on other sites
If you want to get to the bottom of this, I recommend http://forums.devshed.com, they have saved many of my programming courseworks wink_o.gif  thumbs-up.gif

Thanks mate, I've bookmarked that page. I needed a dedicated forum of that type because I'll surely have more questions in the future whilst I tread the long winding lonely windswept, dark path to utopia atop the C++ mountain biggrin_o.gif

Thanks also Vektorboson. Having found a great page on google I now completely understand it and re-reading previous posts (especially yours and Donnervogel's) it now makes alot of sense. Here's the link:

Link

I couldn't post a reply last night even though I kept trying and then the forum went down so I was a bit scared I was going to login today to find 10 copies of my post last night in this thread! Luckily it appears they never made it.

Soooooo,

Basically a reference variable is very similar to a pointer variable. I thought a reference was not a variable, that it was some kind of antidote for a pointer hence the incredible confusion.

A reference variable does not apparently exist in C but it is a new development in C++. Reference variables were intentionally designed to be passed as parameters into functions and basically achieve the same effect as using a pointer variable but with the benefit of not having to de-reference it when inside the function to alter the data stored at the memory address.

In other words, when one passes a variable into a function using a reference any changes to the internal function variable will alter the external value aswell, just as if it were a pointer but you do not have to return anything from the function to get an output.

So all it is, is a neater version of using pointer variables in functions. I suppose in a huge program it certainly would save some code.

I still do not like the way the author of the book has phrased things though, and I think he should have explained that in much more detail before throwing it into the mix. Quite surprising really because other than that the book has been superb. Luckily however you chaps were on hand to sort it out thumbs-up.gif

Share this post


Link to post
Share on other sites

Hmm well references are not really seperate variables. A reference does not occupy memory to store the value of it's type. It's an alternate name to an existing variable. So if you have

<table border="0" align="center" width="95%" cellpadding="0" cellspacing="0"><tr><td>Code Sample </td></tr><tr><td id="CODE">int x; it will occupy some memory to store a variable of type int.

Now when you do <table border="0" align="center" width="95%" cellpadding="0" cellspacing="0"><tr><td>Code Sample </td></tr><tr><td id="CODE">int& rx = x; rx will just be a different name for the same memory location. Unlike a pointer wich actually is a variable itself. A pointer variable has memory alocated to store a memory address. So the value of a pointer variable is a memory address to a value of another variable. Thus the pointer variable has a memory address of it's own wich is different from the address of the variable it points to.

The beauty of references among other things is that if a function returns a reference, then the funtion itself represents an object and can be used as one.

Example:

<table border="0" align="center" width="95%" cellpadding="0" cellspacing="0"><tr><td>Code Sample </td></tr><tr><td id="CODE">

string& message()

{

static string str="Hello" //the string must exist after leaving the function

return str;

}

the function message() now returns a reference to a string and can be handled like an object (in this case the object str of type string)

thus you can do the following things:

<table border="0" align="center" width="95%" cellpadding="0" cellspacing="0"><tr><td>Code Sample </td></tr><tr><td id="CODE">

message() += " World!";

message() = "Hello Universe!";

cout << message().lenght();

as you see you can use the function message() just like the variable str and thus you can use it everywhere where you could use the variable str.

Share this post


Link to post
Share on other sites

Too offtopic for offtopic. If you are serious about learning C++ programming, visit any C++ dedicated site. (Any search engine will give you some).

Share this post


Link to post
Share on other sites
Guest
This topic is now closed to further replies.
Sign in to follow this  

×