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

## Recommended Posts

Abhinash    102

##### 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 on other sites
Aardvajk    13205
Quote:
 Original post by Abhinashnow 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 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 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 on other sites
Guest Anonymous Poster
Shouldnt this be in 'For Beginners'.