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;




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 :(.



'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?



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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...