Sign in to follow this  
Abhinash

change the variables of one function from the other using pointers in c++

Recommended Posts

Abhinash    102
As I always do.. let me tell you guys that till now I am just a beginner of c++ programming and its been just about a week since I started programming in c++. I am a self learner so I kinda GOOGLE for ideas a lot. The better idea to using Global variable in a program is definitely pointers. Pointer is just an adress. You need to keep that in mind if you want to learn how to change the value of a variable using pointers. Ok guys bare with me as I make this analogy. Trust me THIS IS BOUND to clear the concept of pointers. Imagine there are three box A, B, C. the names (A,B and C) are written on the bottom face of the box (I mean to say that you cant just see the name of the box without taking it out and seeing the bottom when it is places somewhere!!). Now put the box A on the table , B under the table and C on the chair, with a red ball in box A. Now call someone who doesnt know which box is which and what each (or any) has. Now give him a cheat with the message "Whats in the box on the table?". He will go to the box on the table(which hapens to be A) and says it loud "a red ball". You should have got the idea yet. You didnt ask the person to go and search in the Box 'A' but since the location "on the table" had Box 'A' he checked THAT particular box. Here the cheat was the "Pointer". It didn't actually have the red ball but let you se what was in the box. No again in the same situation give a secong persont a cheat that reads"take out whatever is in the Box on the table and put a blu ball there" and a third person a cheat that reads" check whats in the box on the table" then the third person's reply will certainly be "a blue ball"... You get it?? Man you just changed the "value" of variable "Box A" without even mentioning its name!!!! Now THATS why I wrote this stupid STORY. You can use the same idea to change the varibles from different functions, and let me tell you this... the process that we use in the program iis not a bit close to the story.. its Wayyyyyyyyyyyyyyyyyyyyyyyyyyyyy shorter... hehe. ok, NOW I TEACH YOU the real stuff. First of all how do we get the adress of the variable?? ok the answer is simple(should be.. now that you understand the concept.. I suppose!!!) an "&" ampersand symbol in front of any variable returns the adress of the variable.... period. (well incase you want to know in which format... its the hexadecimal format.... wo wo wo.. now don't expect me to explain the hexa format.. guys this is a tutorial for pointers remember?? if you want to ask about hexa write to me and I will explain. and if you are a die hard KNOWER.. just like me.. wel why dont you do this .. try cout << &variablemane; it will print the adress of the variable once you execute it.) ok back to the point os the adress of variable var is &var (and period) now you cant just use any variable for the pointer you need pointer variable pointer variable is declared using * infront of the variable name while declaring the type for example: an integer pointer would be: int *IMadeAPointer a string pointer would be??? YES!! you got it .. its => string *ThisIsFun now why did I declare integer and string pointers differently?? well here is the detail whic I THINK IS TRUE .. Seriously I HAVENT FOUND THE REASON IN ANY BOOK WHATSOEVER BUT THIS IS WHAT I THINK: Later we change the value of the actual variable using the pointer so to do that we should be able to use an appropriate type(int string or blah blah blah). So maybe for the FUTURE USE we declare the type straight away) Ok guys so if you do this you store the adress of name in ptr name (these are any variables that I built dont have to be specific but beter use the way I did that is put aptr before the variable to declare the pointer will be easier for you DAWG. aah just a bit Hip Hopping!!!) string name; string *ptrname; ptrname = &name *ptrname = "Baam" cout << name; ok guess what you see in the output?? YEP THE ANSWER IS "Baam" (sory if you guessed "Whatever is in the name variable") so this is how you change the value of the actual variable using pointer variable. remember here in this program if you add a few things like this: string name = "Boom"; string *ptrname; ptrname = &name //suppose the address of name is 0x12ac cout << ptrname << "\n"; *ptrname = "Baam" cout << ptrname << "\n"; cout << name; you willl see the output 0x12ac 0x12ac Baam this shows that the value of the pointer has not changed only the value of the variable the pointer points to has changed. now comes the fun part: using the Functions!! (OH HOW I LOVE FUNCTIONS!!!) I won't explain this though... you should understand it!!!!(Don't disappoin me MY PUPIL!!;)) #include<iostream> #include<stdlib.h> #include<string> using namespace std; void pointer(string *ptr){ /*I have made a few changes now thanks to the guys whose comments are below mine make sure you check the value of the pointer for it might be null and if it is null it may crash the program. So I made a condition that would only use the pointer if the pointer value is not null */ if(ptr){ *ptr = "Changed!!"; } else{ /*include the action that you want to undertake if the pointer leads to nothing!! */ } } int main() { string word = "unchanged"; pointer(&word); cout << word; return 0; } and YESS!!!! You ARE done, no problem if you have the function in separate source file but remember to put a function prototype in the main file... good luck!! [Edited by - Abhinash on August 20, 2006 2:45:52 PM]

Share this post


Link to post
Share on other sites
ToohrVyk    1595
It is very kind and noble of you to teach such concepts. There are two relevant precisions I feel need to be made:

1. Check that pointers are not null whenever you receive them as arguments.


void pointer(string *ptr){
if (ptr) *ptr = "Changed!!";
}


2. The C++ idiom is to use references, not pointers. Your post makes a valid point for the C language, though.


void pointer(string & ptr){
ptr = "Changed!!";
}

pointer(word);


Also, your style, although friendly, is somewhat startling, to say the least.

Share this post


Link to post
Share on other sites
Aardvajk    13205
Quote:
Original post by Abhinash
now why did I declare integer and string pointers differently??
well here is the detail whic I THINK IS TRUE .. Seriously I HAVENT FOUND THE REASON IN ANY BOOK WHATSOEVER BUT THIS IS WHAT I THINK: Later we change the value of the actual variable using the pointer so to do that we should be able to use an appropriate type(int string or blah blah blah). So maybe for the FUTURE USE we declare the type straight away)


That is correct. The compiler needs to know the type of the item being pointed at in order to allow for operations on the dereferenced pointer, and to know the size of the item pointed at in order to perform pointer arithmetic correctly.

Share this post


Link to post
Share on other sites
ToohrVyk    1595
A null pointer evaluates to false, while a non-null pointer evaluates to true. Therefore:


if (ptr) { /* ptr is not null */ }
else { /* ptr is null */ }


The following is redundant:


if (ptr != NULL) // equivalent to: if (ptr)

Share this post


Link to post
Share on other sites
mikeman    2942
Quote:

I didn't actually get what you meant while checking the value of the pointer to be null. I got its better to use referrences though. Anyways, is this what would make it better , I mean if I have to check whether the pointer value in null I would do this in the function


"if (ptr)" means "if ptr is something other than 0(NULL=0)". You have to check that, because if the user of the function accidentaly passes a pointer which holds the invalid address "0", and the function tries to read/write to that address, the program will crash. Actually, the program will crash when using any pointer that holds a memory address that is invalid, ie that you can't read/write to because that memory location has not been allocated for use by the program. With references these problems don't exist. In any situation that you're allowed to choose between using a reference and a pointer, absolutely go with reference.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this