初始化一个整数指针,其指针地址本身就是一个值

Initialising an integer pointer with a value at its pointee's address there itself

例如,考虑;

char* a = "coding is fun";

我了解到这一行将创建一个指针并将字符串文字放在其指针的地址中。

解引用运算符实际上是在那里完成它的工作,还是它只是语法的一部分,只是告诉编译器创建一个指针数据类型?

因为如果它真的在那里作为取消引用运算符工作,那么 => int* a = 5; 也应该将 5 的值放在指针 a 的指针地址中。

如果不是,那么前面的代码片段如何有效?

如果像

这样的语句
 char* a = "coding is fun";

取消引用运算符 * 用于任何取消引用。这里的*可以认为是类型本身的一部分,表示该变量是指针类型,即变量a的类型是char *,即指向 char.

的指针

该语句基本上是创建一个未命名数组,用 coding is fun 和空终止符填充它,然后通过将 未命名数组 分配给指针,使指针指向该数组的第一个元素,因为根据 C11,章节 §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;

有效语法 无效用法 ,因为在那里,您尝试 store int5 作为指向 int 类型的指针,这是高度平台定义的行为。

它是有效的,因为语言规范说它是。

您可以期待 C 语法的 100% 对称性和正交性,但您会失望的。 :)

基本都能看懂

char *a = "coding is fun";

作为以下的快捷方式:

char a_string[] = "coding is fun";
char *a = a_string;

当然,第一行是以下内容的快捷方式:

char a_string[] = { 'c', 'o', 'd', 'i', 'n', 'g', ' ', 'i', 's', ' ', 'f', 'u', 'n', '[=12=]' };

显然,a_string 这个名字从未被真正引入,但这就是它在幕后工作的方式。

整数不存在这样的快捷方式,但这很好,因为也不存在与双引号等效的东西(您的 int *b = 5; 示例看起来很简单 5,而字符串示例有双引号中的一串字符)。

字符串字面量成为指向进程内存只读部分中数组的指针。 (C 标准中没有这样的东西,但这就是实际工作的方式。)

所以你实际拥有的是

char * a = <the said address>.

整数值没有这样的等价物,所以不,你认为行不通。

int* a = 5 设置变量 a 指向地址 5.

char* a = "coding is fun" 将变量 a 设置为指向 "coding is fun" 字符串的地址,根据 compiler/linker 将其放置在可执行映像中的位置确定。

通常,它将驻留在只读段中,但这不是 C 语言标准规定的。

For instance, consider;

char* a = "coding is fun";

I have understood that this line will create a pointer and put the string literal at its pointee's address.

你搞反了。该行声明了一个 char * 类型的变量 a(指向 char 的指针),并使用指向给定字符串文字第一个字符的指针值对其进行初始化。文字本身代表一个 char 的数组。它的位置由编译器选择,与 a 的位置无关,当然也与 a 未初始化时的不确定值无关。

Is that dereference operator actually doing its job there or is it just a part of the syntax and is just to tell the compiler to create a pointer data type?

它根本不是解引用运算符;它是 a.

类型规范的一部分

Because if it really is working as a dereferencing operator there than => int* a = 5; should also put the value of 5 at the pointee's address of pointer a.

您将 a 定义为 int * 的替代定义无效,因为表达式 5 的类型为 int,并且对指针类型变量的赋值需要该值分配为具有兼容的指针类型,具有类型 void *,或为空指针常量。然而,许多编译器仍然会接受它,但通常会发出警告,因为 C 允许将 int 转换为指针(技术上需要强制转换)。在任何情况下,结果都不是一个可以取消引用以获得值 5 的指针,而是一个可以 转换 5 的指针。这就是求值*a和求值(int)a.

的区别

If not, then how is the former code snippet valid?

一个字符串文字的数组类型为 n char,其中 nchars 的数量在文字中,加上一个终止符。在几乎所有的 C 上下文中,当计算数组类型的(子)表达式时,结果是指向第一个数组元素的指针。在评估字符串文字的情况下,结果指针的类型是 char *,这也是 a 的声明类型。将给定类型的值分配给具有完全相同类型的非 const 变量可能有什么问题?