0

I've always never fully understood pointers. I'm writing this dinky blackjack game for fun on the side of my studies, and I need confirmation that this use of pointers is legitimate so I can fully understand what they do.

currently this is an example of the program and function i'm using:

void dealcard(int hand){
    hand+=rand()%10+2;
 }

int()main{
   int playerHand;
   ...
   *blackjack stuff*
   ...
   if(hit){
      deal(hand);
        }

now if I'm correct, the above would not work as I intend because the function uses a copy of the variable that is cleared before it can be applied to the original, and hand would never be changed.

if I changed it to something like

     int b;
     int *hand;
     hand=&b;

and changed the function declaration to include the *, then that would be correct.

I'm really trying hard to understand pointers and i'd appreciate any help or confirmation on this so I can understand the basic usefulness of them.

gr33kbo1
  • 303
  • 4
  • 5
  • 15
  • lots of guys asked similar question before, read "Related" questions in this page before anyone answers this question :-) – tdihp Sep 11 '13 at 01:54
  • Are you sure about it being C++? // your code looks much more like C to me than C++. – Mansueli Sep 11 '13 at 01:54
  • sorry for the confusion. i was reading an article about pointers that used C as an example instead of C++. also i apologize if this question is a duplicate, i realize that the community here is striving hard to keep the standard of the website high – gr33kbo1 Sep 11 '13 at 01:58
  • You'd have to change to `*hand += rand()...` as well. The basic usage would be correct, but you won't really understand why they're useful by just replicating what's easy enough to do with a plain `int`. – Crowman Sep 11 '13 at 02:39
  • BTW: Interesting card distribution `hand+=rand()%10+2`. – chux - Reinstate Monica Sep 11 '13 at 03:34

1 Answers1

2

That would be correct. It would also be C rather than C++ :-) The way you would do it in that case would be:

void dealcard (int *pHand) {
    *pHand += rand() % 10 + 2;
}
:
int hand = 0;
dealcard (&hand);

C++ has this nifty thing called references which means you no longer have to perform the sort of addressing gymnastics required by C. You can write your function thus:

void dealcard (int &hand) {
    hand += rand() % 10 + 2;
}
:
int hand = 0;
dealcard (hand);

And, as an aside, not really relevant to your question:

int()main{

is not one of the accepted signatures for main, I suspect you meant:

int main() {
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953