简体   繁体   中英

Why are there two different ways of initializing a pointer in C

The first way looks like this:

int *p_number = &number;

And the second like:

int *p_number;
p_number = &number;

I don't get why the first way look as it looks, because I get that p_number is the address of int *p_number and we are basically giving p_number the address of number with the & operator. But why do we initialize *p_number with &number ? Wouldn't that mean that the pointee of p_number is the address of number?

I believe what's confusing you is the syntax

int *p_number = &number;

well, you can rewrite it as

int* p_number = &number;

which is same as

int *p_number;
p_number = &number;   

The first one is actually a combined step of definition and initialization.

Only the first of these is initializing the pointer. The second creates an uninitialized pointer, and then assigns a value to it. The net effect of these is the same (you have a pointer variable that points at a particular thing), and the code generated by the compiler is likely identical.

The thing that seems to be confusing you is that the syntax of declarations and initializers is subtly different from the syntax of assignments. In particular, a * in a declaration means that you are declaring a pointer and not dereferencing it, while in an expression, a * means that you are dereferencing. This kind of subtle difference is considered a wart by some and a feature by others.

int *p_number = &number;

This consists of two parts: a declartion of p_number , followed by its initializer = &number (read as "is address of number").

int *p_number;
p_number = &number;

This does the same, but is conceptually a bit different. The first line is the declaration (same as in previous example). The second line is an assigment and it is a statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM