Jump to content

Int*'s Don't Like To Be Ints


Recommended Posts

Well, I'm getting an invalid conversion error on some source code (yea, ONLY ONE ERROR WHILE DEALING WITH POINTERS! I'm good :D!) that uses a pointer to pass an argument to a function. It's on my computer right now, which is offline. So, I'll be lazy and only post the code that really counts:

 

int function(int*);
int nNumberEntered;
int* pPointar = &nNumberEntered;

//have the user enter a number, blah blah blah... call function with pPointar as the argument

int function(int* pOtherPointar) {
     int x = rand() %10;
     int newNumber = x + pPointar;
     return newNumber; //Because I don't know what else to return, alright?
}

 

So... any ideas?

 

 

EDIT: Turns out, all I needed to do was change:

 

int newNumber = x + pPointar;

 

To:

 

int newNumber = x + *pPointar

 

 

Daaaaamn, I'm getting good. ONTO POLYMORPHISM!

Share this post


Link to post
Share on other sites

You got it man :) Welldone!!!

 

Incase you don't know, when you're working with a pointer, *variable gets the value. So like.. when you passed the pointer in to that function when you do anything with "variable" that is actually the memory address, *variable is like "follow that memory address and get the value". Get it? :)

Share this post


Link to post
Share on other sites

No... I don't...

I quit :(.

511139[/snapback]

 

'tis easy really. How about this explanation..

 

You know an int stores a number, right? You know a char stores a single character, right? Now just think a pointer storing a memory address, whether it be an int, char, whatever.

 

So lets say...

 

int i = 1;

char c = 'a';

int *p = 0xffa4; (which wouldn't actually work by the way)

 

So in "i" goes 1. In "c" goes the letter a and in "p" (not *p) goes a memory address 0xffa4 (whatever the hell that might be). Now a * in a variable declaration means it's a pointer. A * in actual code means follow the memory address stored in the variable.

 

So cout << *p means go to memory address 0xffa4 and print whatever value is there.

 

I don't know if I can explain it any easier than that. The picture might also help.. a bit?

 

 

Share this post


Link to post
Share on other sites

So something like printf("%x",p); would display the address stored in p, but not the value that the address points to?

511144[/snapback]

 

That's right! and to display the value would be *p, because *p follows that address to the value :rolleyes:

Share this post


Link to post
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
×
×
  • Create New...