Question about pointers?

K

kazack

I am under the the impression that a variable is what is stored in a memory
address and a pointer is the memory address of the variable?

I was looking to use a function that does not return a value void
whatever(whatever) and not have a variable global but in main and change the
value in the void whatever function.

using namespace std;
void whatever(int);

int main()
{
int test;
test = 1;
whatever(test);
return 1;
}
void whatever(int testing)
{
&test = testing
// The above line I am unsure of how to exactly do it.
//what would I need to change in order to change the
//value of test in main though the whatever function
//without actually having to return a value.
}
Thank you,
Shawn Mulligan
 
A

Artie Gold

kazack said:
I am under the the impression that a variable is what is stored in a memory
address and a pointer is the memory address of the variable?

I was looking to use a function that does not return a value void
whatever(whatever) and not have a variable global but in main and change the
value in the void whatever function.

using namespace std;
void whatever(int);

int main()
{
int test;
test = 1;
whatever(test);
return 1;
}
void whatever(int testing)

Just make the above:
void whatever(int& testing)

and any changes made to `testing' will be reflected in the caller.
{
&test = testing
// The above line I am unsure of how to exactly do it.
//what would I need to change in order to change the
//value of test in main though the whatever function
//without actually having to return a value.
}

....and *please* look up `reference' in your favorite C++ documentation.

HTH,
--ag
 
K

kazack

Is there anyway possible also with the use of pointers to reference a
variable, that is not global and is not passed directly into a function?

Or does it have to be global or passed?

Thank You,
Shawn Mulligan
 
R

Rolf Magnus

kazack said:
I am under the the impression that a variable is what is stored in a
memory address and a pointer is the memory address of the variable?

More or less. You could rather say that a variable must be somewhere in
memory, and every piece of memory has an address. A pointer can hold
such an address.
I was looking to use a function that does not return a value void
whatever(whatever) and not have a variable global but in main and
change the value in the void whatever function.

using namespace std;
void whatever(int);

int main()
{
int test;
test = 1;
whatever(test);
return 1;
}
void whatever(int testing)
{
&test = testing
// The above line I am unsure of how to exactly do it.
//what would I need to change in order to change the
//value of test in main though the whatever function
//without actually having to return a value.

You cannot change the variable 'test' from main this way, because it is
passed to the function by value, i.e. a copy of it is made, and your
whatever() function only sees that copy. Any modification to the
'testing' parameter will only modify the local copy in the function.
For doing what you want to do, you need to pass by reference, i.e.:

void whatever(int& testing)
{
//do some changes to testing
}

This way, testing will be a reference, which means that it is just
another name for the variable 'test' from main(), so any change to
'testing' in whatever() will result in a changed 'test' in main().
 
M

Mike Wahler

kazack said:
Is there anyway possible also with the use of pointers to reference a
variable, that is not global and is not passed directly into a function?

Yes.

#include <iostream>

void changeit(int *arg)
{
*arg = 42;
}

int main()
{
int i = 0;
std::cout << i << '\n'; /* prints 0 */
changeit(&i)
std::cout << i << '\n'; /* prints 42 */
return 0;
}

This is the way it's done in C (and can also be done this
way in C++, although references are more 'idiomatic'
in C++).
Or does it have to be global or passed?

All functions have access to a 'global' object.
This is the reason why such 'globals' should be
avoided if possible, it leaves open the possibility
of a function changing something which it should
not.


-Mike
 
J

Jon Bell

I am under the the impression that a variable is what is stored in a memory
address and a pointer is the memory address of the variable?

I would say that a variable is a memory location whose contents can be
changed (unless it is declared as const), and a pointer is a variable that
contains a memory address. That address is usually the address of another
variable (or at least it's intended to be).
 
E

Evan

kazack said:
Is there anyway possible also with the use of pointers to reference a
variable, that is not global and is not passed directly into a function?

You have to pass it in. If a variable is local to a function and you
call another function, the only way to access that variable is by
passing it in by reference or it's address as a pointer.



Actually this isn't exactly true... you can store the address in an
external pointer, a la:

int *bad_example;

int main() {
int value_to_change = 10;
bad_example = &value_to_change;
foo();
cout << value_to_change; // Should print 20
}

void foo() {
*bad_example = 20;
}

But you *do* need a global variable. And at any rate, the above
example is bad bad and bad.

It violates good design rules left and right. Global variables are
shunned in general, and using one to change a local variable is even
worse. Generally what a function does should be clear from it's name
and the parameters; foo() above doesn't make clear what it is doing at
all. So if your function needs to change another value, either pass in
the value as a reference parameter (or pointer; some people prefer
this for some good reasons, though syntactically references are
clearer) or return it.
 
K

kazack

Wow I should of just stuck with VB. I am learning alot between the book I
am using and you guys here.

The sample program I am writing from the book which I have working is to
JUST read i a file with three sides to a triangle, multiple triangle
dimensions listed, and tell what type of triangle it is if it is a valid
triangle. Well I got that done with no problem but I like pushing the
envelope a little bit more than just doing what they ask. I have added the
ability to check for file existance, which was OS dependant until I was told
about cerrno header file. Big help, I didn't even know this existed, it's
not in my book anywhere, a matter of fact in none of my books I have and I
have 3 c++ books and 2 c books. Now I am learning about pointers 2 chapters
ahead of time to accomplish what I need done. I need to call a function
from within a function from within a function and I did not feel like having
to pass variables from the first function to the second function so I can
work with it in the third. Is this the standard way to do things? Or is
this bad coding habits? I am teaching myself here as you guys can prolly
tell by my questions i am and have asked?

Is it good or bad to pass a variable into a function just to beable to pass
it into another function so it can be used?

Thank you guys again for your help,
Shawn Mulligan
 
C

Charles LaCour

kazack said:
Wow I should of just stuck with VB. I am learning alot between the book I
am using and you guys here.

The sample program I am writing from the book which I have working is to
JUST read i a file with three sides to a triangle, multiple triangle
dimensions listed, and tell what type of triangle it is if it is a valid
triangle. Well I got that done with no problem but I like pushing the
envelope a little bit more than just doing what they ask. I have added the
ability to check for file existance, which was OS dependant until I was told
about cerrno header file. Big help, I didn't even know this existed, it's
not in my book anywhere, a matter of fact in none of my books I have and I
have 3 c++ books and 2 c books. Now I am learning about pointers 2 chapters
ahead of time to accomplish what I need done. I need to call a function
from within a function from within a function and I did not feel like having
to pass variables from the first function to the second function so I can
work with it in the third. Is this the standard way to do things? Or is
this bad coding habits? I am teaching myself here as you guys can prolly
tell by my questions i am and have asked?

Is it good or bad to pass a variable into a function just to beable to pass
it into another function so it can be used?

Thank you guys again for your help,
Shawn Mulligan

The program you are writing doesn't sound particularly complicated, so I'm
guessing that it is not unreasonably long. Why don't you post your code and
maybe someone can point out any flaws in your reasoning. Yes, it can be
annoying to pass a value from one function to another, but it's not bad
coding.

By the way, to the best of my knowledge, VB won't allow you to get the
address of a variable that is inside another function, so I don't see how
staying with VB would have helped you.
 
E

Evan

kazack said:
The sample program I am writing from the book which I have working is to
JUST read i a file with three sides to a triangle, multiple triangle
dimensions listed, and tell what type of triangle it is if it is a valid
triangle. Well I got that done with no problem but I like pushing the
envelope a little bit more than just doing what they ask.

This is good.
I have added the
ability to check for file existance, which was OS dependant until I was told
about cerrno header file.

cerrno? What are you doing to open files? This is a header inherited
from C that shouldn't be necessary unless I'm missing something.
Big help, I didn't even know this existed, it's
not in my book anywhere, a matter of fact in none of my books I have and I
have 3 c++ books and 2 c books.

This is not a surprise; even in Stroustrup I can't seem to find
mention other than in the list of standard headers.
Now I am learning about pointers 2 chapters
ahead of time to accomplish what I need done. I need to call a function
from within a function from within a function and I did not feel like having
to pass variables from the first function to the second function so I can
work with it in the third. Is this the standard way to do things? Or is
this bad coding habits?

It depends on the functions; I'd have to see your specific example to
give you my opinion. However, there are times when a function doesn't
do anything with one or more of its argument except pass it to another
function.
I am teaching myself here as you guys can prolly
tell by my questions i am and have asked?

That's what we're here for. If we weren't learning there'd be no
purpose for the newsgroup. :p
 
K

kazack

Welp after writing and rewriting I hope I have code that is 100% standard
with the exception of the void fileexistcheck(filename) that is OS
dependant. I hope the rest of it is totally standard. I started out with
value returning functions, then switched in mid gear to change it all to
void functions and do as much as I could with pointers. So I would like to
have this code critiqued. I would like to know for my own benefit, Is it
better to have a value returning function or to pass a pointer?

Welp below here is the code in full. I do not have it documented although
the names of the variables and functions are self
explanatory.----------------------------------------------------------------
----------------------------------------------------------------------------
--------------------------------------------------------------
#include <iostream>
#include <io.h>
#include <cstring>
#include <string>
#include <fstream>
#include <cctype>
using namespace std;

void selectfilename(string&);
void fileexistcheck(string, bool&);
void readdata(string);
void NotValid(int, int, int);
void Equal(int,int,int);
void Isos(int,int,int);
void triangle(int,int,int,int);
void createfile(string);

enum Triangles{Scalene,Isosceles,Equalateral,Invalid,Hold};
Triangles Entered = Hold;

int main()
{
string filename;
char yeahneah;
bool exists;
selectfilename(filename);
fileexistcheck(filename,exists);
if (exists == true)
{
readdata(filename);
}
else
{
cout << endl << filename << " does not exist." << endl;
cout << "Would you like to select a different filename? (Y/N): ";
cin >> yeahneah;
if (toupper(yeahneah) == 'Y')
{
main();
}
else
{
cout << "Would you like to create this file? (Y/N):";
cin >> yeahneah;
if (toupper(yeahneah)=='Y')
{
createfile(filename);
readdata(filename);
}
}
}
return 0;
}

void selectfilename(string& filename)
{
cout << "Please Enter The Data File You Would Like To Use: ";
cin >> filename;
}


void fileexistcheck(string filename, bool& exists)
{
if ((_access(filename.c_str (),0))!=-1)
{
exists = true;
}
else
{
exists = false;
}
}





void readdata(string filename)
{
int sidea;
int sideb;
int sidec;

ifstream inData;
inData.open(filename.c_str());

inData >> sidea >> sideb >> sidec;

while(inData)
{

NotValid(sidea, sideb, sidec);
if (Entered == Invalid)
{
triangle(Entered,sidea,sideb,sidec);
}
else
{
Equal(sidea,sideb,sidec);
if (Entered == Equalateral)
{
triangle(Entered,sidea,sideb,sidec);
}
else
{
Isos(sidea,sideb,sidec);
if (Entered == Isosceles)
{
triangle(Entered,sidea,sideb,sidec);
}
else
{
Entered = Scalene;
triangle(Entered,sidea,sideb,sidec);
}
}
}
inData >> sidea >> sideb >> sidec;
}
inData.close();
}

void Isos(int sidea, int sideb, int sidec)
{
Entered = ((sidea == sideb) || (sideb==sidec) ||
(sidec==sidea))?Isosceles:Invalid;
}

void NotValid(int sidea,int sideb,int sidec)
{
Entered = ((sidea + sideb > sidec) && (sideb + sidec > sidea) && (sidea +
sidec > sideb))?Hold:Invalid;
}

void Equal(int sidea, int sideb, int sidec)
{
Entered = ((sidea == sideb) && (sideb==sidec) &&
(sidec==sidea))?Equalateral:Hold;
}

void triangle(int Entered,int sidea, int sideb, int sidec)
{

switch(Entered)
{
case 0 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
<<" makes this a Scalene Triangle"<<endl; break;
case 1 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
<<" makes this an Isosceles Triangle"<<endl; break;
case 2 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
<<" makes this an Equalateral Triangle"<<endl; break;
case 3 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
<<" makes this an Invalid Triangle"<<endl; break;
}
}


void createfile(string filename)
{
char choice;
string sidea;
string sideb;
string sidec;

ofstream outData;




cout << "Please enter A to Add a triangle or Q to stop adding triangles to
this file: ";
cin >> choice;
while ((toupper(choice) != 'A') && (toupper(choice) != 'Q'))
{
cout << "Please enter A to Add a triangle or Q to stop adding triangles to
this file: ";
cin >> choice;
}

while (toupper(choice) =='A')
{
outData.open(filename.c_str(), ios::app);
cout << "Enter Side 1 of this triangle: ";
cin >> sidea;
cout << endl << "Enter Side 2 of this triangle: ";
cin >> sideb;
cout << endl << "Enter Side 3 of this triangle: ";
cin >> sidec;
outData << sidea << " " << sideb << " " << sidec << endl;
outData.close();
cout << "Please enter A to Add a triangle or Q to stop adding triangles to
this file: ";
cin >> choice;
}
}
 
E

Evan

kazack said:
Welp after writing and rewriting I hope I have code that is 100% standard
with the exception of the void fileexistcheck(filename) that is OS
dependant. I hope the rest of it is totally standard.
Yes

I would like to know for my own benefit, Is it
better to have a value returning function or to pass a pointer?

Almost always returning a value is preferable, at least IMO. See my
comments in code.

#include <iostream>
#include <io.h>
#include <cstring>
#include <string>
#include <fstream>
#include <cctype>
using namespace std;

[Function prototypes omitted]

enum Triangles{Scalene,Isosceles,Equalateral,Invalid,Hold};
Triangles Entered = Hold;

int main()
{
string filename;
char yeahneah;
bool exists;
selectfilename(filename);
fileexistcheck(filename,exists);

Why oh why do you do this? :p One of the reasons that some people
don't like reference passing (and one reason Java doesn't have it in
the sense C++ does, and one reason why C# requires the keyword ref in
the function call, as in fileexists(filename, ref exists)) is that it
is not apparent at all that the function changes the value of exists.
Returning the bool then saying

exists = fileexistcheck(filename);

is *much* more readable for anyone I've talked to. Passing values out
of functions in the way you did has uses in some cases, for instance
if you need two values returned (e.g. a pointer and a bool if the
pointer is valid), but I'd say change this. And if I were your boss
I'd say change it.
if (exists == true)

Plus, here you could say
if (fileexistcheck(filename) == true)
if you did that. You can compose function calls.
{
readdata(filename);
}
else
{
cout << endl << filename << " does not exist." << endl;
cout << "Would you like to select a different filename? (Y/N): ";
cin >> yeahneah;
if (toupper(yeahneah) == 'Y')
{
main();
}
else
{
cout << "Would you like to create this file? (Y/N):";
cin >> yeahneah;
if (toupper(yeahneah)=='Y')
{
createfile(filename);
readdata(filename);
}
}
}
return 0;
}

void selectfilename(string& filename)
{
cout << "Please Enter The Data File You Would Like To Use: ";
cin >> filename;
}

Case in point of what I said earlier: before I got here I had a
comment after the declaration of filename in main that said "I assume
filename is initialized somewhere in here" because it was not clear at
all that selectfilename sets its argument to the filename.
void fileexistcheck(string filename, bool& exists)
{
if ((_access(filename.c_str (),0))!=-1)
{
exists = true;
}
else
{
exists = false;
}
}

Here you can just test to see if the fstream you attempt to open in
the next function is good. Like you have a while(inData) loop; this
will not run if the file does not exist and is not created (if you
want to stop creation you need to pass another argument to the
constructor). It's not entirely the same thing, but it's probably
acceptable.
void readdata(string filename)
{
int sidea;
int sideb;
int sidec;

ifstream inData;
inData.open(filename.c_str());

inData >> sidea >> sideb >> sidec;

while(inData)
{

NotValid(sidea, sideb, sidec);
if (Entered == Invalid)
{
triangle(Entered,sidea,sideb,sidec);

As the program is structured now, there is no need to pass Entered
since its global anyway.
}
else
{
Equal(sidea,sideb,sidec);
if (Entered == Equalateral)
{
triangle(Entered,sidea,sideb,sidec);
}
else
{
Isos(sidea,sideb,sidec);
if (Entered == Isosceles)
{
triangle(Entered,sidea,sideb,sidec);
}
else
{
Entered = Scalene;
triangle(Entered,sidea,sideb,sidec);
}
}
}
inData >> sidea >> sideb >> sidec;
}
inData.close();
}

[Other functions omitted; no comments]

I would move the variable Entered into the readdata function. Then
pass it as a parameter to the other functions like you do with
triangle.
[Several functions omitted]

void triangle(int Entered,int sidea, int sideb, int sidec)
{

switch(Entered)
{
case 0 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
<<" makes this a Scalene Triangle"<<endl; break;
case 1 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
<<" makes this an Isosceles Triangle"<<endl; break;
case 2 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
<<" makes this an Equalateral Triangle"<<endl; break;
case 3 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
<<" makes this an Invalid Triangle"<<endl; break;
}
}

"Magic numbers" in you switch statement. You should use the constants
defined with the Triangle enum instead. case Scalene:, case: Isoceles,
etc. That's what they are there though.
[Several more functions omitted]

Sometime in the next couple days I'll post code the way I'd attack the
problem for comparison purposes. I don't have time at this exact
moment but should be able to find time in a couple days, so check
back. (I'll also address the file existance problem.)

Evan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top