What is the problem on below program? about pointer


int foobar( int *pi) {
*pi = 1024;
return *pi;
}

int main() {
int *pi2=0;
int ival = foobar( pi2);
return 0;
}

I am a beginner and not familiar with this pointer. Can anyone show me some hints?
your 'pi2' (and therefore your 'pi') pointer don't actually point to anything.


A pointer tells the compiler where to look for another variable. That is, it "points to" that variable.

1
2
3
4
int* pi2 = 0;  // here you are making a pointer point to null (nothing)
*pi2 = 1024;  // this attempts to put the value of 1024 in whatever variable
  // pi2 points to.  But since pi2 points to nothing, this is trying to put 1024 in 'nothing'
  //  which will likely cause your program to crash 




To make this work, you pointer has to actually point to something:

1
2
3
4
5
6
7
8
int variable = 0;  // a variable
int* pointer = &variable;  // a pointer that points to 'variable'

*pointer = 5;  // assign 5 to whatever 'pointer' points to
   // (ie, since pointer points to variable, this effectively is like saying
   //   variable = 5;)

cout << variable;  // prints 5 
Last edited on
Thanks, Disch. I got it. What is missing is a variable.
[
int foobar( int *pi) {
*pi = 1024;
return *pi;
}

int main() {
int variable=0;
int *pi2=& variable;
int ival = foobar( pi2);
return 0;
}

]
Yes. That will work.

You'll notice that after foobar is called, both 'variable' and 'ival' == 1024.
Topic archived. No new replies allowed.