Reputation: 567
I want to learn very basics of pointers in C language
What is the difference between below two ways? Which is correct? Which is more preferable?
int a = 20;
int *p = &a ;
or
int a = 20;
int *p ;
p = &a ;
Upvotes: 1
Views: 194
Reputation: 529
The difference here is not related to pointers, but to declaring and initializing variables in general.
For example, you can do:
int a; // this declares the variable a as an integer
a = 20; // this initializes the variable a with the value 20.
OR, you can combine these two into one line:
int a = 20; //this now both declares and initializes the variable a.
The difference is that you can only declare a variable ONCE, but you can assign a value to it as many times as you like.
So if you were to write
int a = 20;
and then later on in your code you wanted to change the value of a to say, 30, here you can ONLY write
a = 30;
You could not write int a = 30;
again, because you cannot declare a again, a has already been declared.
This difference is what you are illustrating with your pointers.
int a = 20; //variable a is declared as an int and also initialized to the value 20
int *p = &a ; //pointer p is declared and initialized with the address of a.
or
int a = 20; // variable a is declared as an int and also initialized to the value of 20
int *p ; // pointer p is declared
p = &a ; // pointer p is assigned the value that is the address of variable a.
You could also have written
int a;
a = 20;
int *p;
p = &a;
And this is still correct, and produces exactly the same result.
Upvotes: 1