pointer 101 question

I read a book
It said
1
2
3
4
5
6
7
8
9
int main(){
int i;
int *p;
p = &i;  
f(p);}
void f(int *j)
{
*j=100;
}



One thing I don't understand
p = &i; // My understand is that p keep the address I


Q1) What if I change int *p; to int p; ??
'p' should still keep the int address of I. *j = 100 should still assign 100 to the same address. Is it??

Q2) What if I change p = &i; to *p = &i; ??

Last edited on
1. Wrong. The compiler will complain about trying to assign a pointer to a non-pointer. To that, you need at least this much code:
1
2
3
4
5
6
int p=(int)&i;
f(p);
//...
void f(int p){
    *(int *)p=100;
}

It will compile, but DON'T do this.

2. The compiler will again complain about trying to assign a pointer to an integer, but it's even more dangerous than the previous case.
If you do *p=(int)&i;, the compiler will let it pass, but odds are that the program will crash when you try to run it because p is pointing to nothing valid, and the assignment tries to write to that location.
Topic archived. No new replies allowed.