指针的两种不同类型的星号位置

Two different types of asterisk locations for a pointer?

本文关键字:位置 两种 指针 同类型      更新时间:2023-10-16

假设你有这个。

 int fry = 50;

现在 wen 做一个指针并引用值,星号可以有两种不同的放置方式:

 int* d1 = &fry;

和。。。

 int *d1 = &fry;

我想知道有什么区别以及最好使用每种情况?谢谢!

没有区别。你甚至可以做int*d1int * d1.

在我看来,您应该更喜欢int *d1:此选择在避免混淆方面特别有用:

int* d1, d2;
int *d1, d2;

这些语句都声明一个整数和一个指向整数的指针。第一个版本看起来很有误导性。

你给出的两个例子没有区别。至于你应该使用哪个,请遵循你正在使用的代码的风格。

但请注意,* 绑定到变量,而不是它们类型。因此

int *this_is_a_pointer, this_is_just_an_int;

int* this_is_a_pointer, this_is_just_an_int;

都是一样的。如果你需要这样的东西,我实际上会写以下任何一篇以避免任何混淆

int* this_is_a_pointer;
int this_is_just_an_int;

int *this_is_a_pointer;
int this_is_just_an_int;

取决于所使用的样式。