C Board  

Go Back   C Board > General Programming Boards > FAQ Board

 
 
LinkBack Thread Tools Display Modes
Old 10-16-2001, 10:22 AM   #1
Registered User
 
Join Date: Oct 2001
Posts: 101
'&' and '*'

I'm always confusing with the '*' and '&' in C++. Would anyone mind telling me the differences before them? Does any website talk about '*' and '&'? Thank you!~
DramaKing is offline  
Old 10-16-2001, 11:28 AM   #2
Registered User
 
Join Date: Sep 2001
Posts: 156
When defining a pointer we use *:
int * pI = NULL;
char* pC = NULL;
in the above case both pointers have been set to NULL or do not point to anything.

The & is reference to or address of, so below:
int i =0; //i = 0
char c = ' ';c = a space ' ';

pI = &i;
pC = &c;

we assign the address of i to pointer pI and the address of c to Pc. Now we can use the * to dereference our pointers, which is to get the value of the item they point to:

int t = *pI; this expression will resolve to setting t to 0 because pI points to i and i == 0.
*pI = 10; this expression will resolve to setting i to 10 because pI points to i.

char ch = *pC; this expression will resolve to to assigning ' ' (a space) to ch.
*pC = 'A'; this expression will resolve to setting c to 'A'.

now comes the wacky part of a & ( reference ). I can define a reference to i;

int &rI = i; //rI will always equal i and vice a versa

The reference (&) is like a constant pointer that is automathically dereferenced. It is usually used for function argument lists and function return values.

I hope that helps. For more info I would recommend reading "Thinking in C++ second edition" by Bruce Eckel.
Dang is offline  
 

Thread Tools
Display Modes

Forum Jump


All times are GMT -6. The time now is 05:25 AM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22