例如,考虑;
char* a = "coding is fun";
我知道这一行将创建一个指针并将字符串文字放在它的指针地址处。
解引用运算符实际上是在那里完成它的工作,还是它只是语法的一部分,只是告诉编译器创建一个指针数据类型?
因为如果它真的在那里作为解引用运算符工作,那么 => int* a = 5;
也应该将 5 的值放在指针 a 的指针地址中。
如果不是,那么前面的代码片段如何有效?
最佳答案
如果像这样的语句
char* a = "coding is fun";
解引用运算符 *
不用于任何解引用。这里的*
可以看作是类型本身的一部分,表示该变量是指针类型,即变量a
的类型> 是 char *
,即指向 char
的指针。
该语句基本上是创建一个未命名数组,用空终止符填充 coding is fun
然后,通过将 未命名数组 分配给指针,使指针指向该数组的第一个元素,因为根据 C11
, chapter §6.3.2.1
Except when it is the operand of the
sizeof
operator, the_Alignof
operator, or the unary&
operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. [...]
要补充一点,
int* a = 5;
是有效的语法但无效的用法,因为在那里,您尝试存储 int
值5
作为指向 int
类型的指针,这是高度平台定义的行为。
关于c - 初始化一个整数指针,其指针地址本身就是一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40404209/