Reputation: 85
I see two option to assign a pointer
1.
int p=5;
int *r=&p
2.
int p
int *r;
r=&p;
Why do they use in 1 with asterisk and in two without?
Upvotes: 2
Views: 1808
Reputation: 374
because in 1. int *r=&p
is declaration.
and in 2. r=&p
is not in declaration.
asterix (*) means data type of pointer.
For more information, you can read here
Upvotes: 0
Reputation: 20726
The second is exactly the same. The first example declares the variable and assigns value too in one go. The declaration part needs the *
, as that specifies that this variable will store a pointer to an int value. The value assignment part doesn't need this kind of thing, since the variable r
is already declared to be a pointer.
Upvotes: 0
Reputation: 8604
Case 2: int *r
is a declaration of an uninitialized pointer to int
; r = &p
is an assignment which sets the value to the pointer.
Case 1: int *r=&p
is a declaration of a pointer to int
which is initialized with the address of p
.
Upvotes: 0
Reputation: 206689
You should read this:
int *r [...]
as:
(int *) r [...]
The type of r
is int *
. If you look at it that way, you'll see that both versions are identical.
Upvotes: 8
Reputation: 409166
The two alternatives are actually the same. The first is just less text.
The asterisk, when used in a declaration like int *r
, is what tells the compiler that the variable r
is a pointer.
Upvotes: 3