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

标签 c string pointers string-literals

例如,考虑;

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;

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

关于c - 初始化一个整数指针,其指针地址本身就是一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40404209/

相关文章:

c - 仅分配一次时,3 个字符串获得相同的值

arrays - 在数组中查找与数组具有相同均值的对

string - 将 char 分配给 string 时如何解决 W1047/W1068 警告?

Java:如果一行包含特定单词,则打印一次

c - 光环交换在 MPI 中无法正常工作

c - 为什么不能重新分配字符串数组,但是字符串指针可以使用C语言?

r - 如何在R中的字符中查找字符串

c - 在 C 中动态构建二叉树时指针分配的问题

pointers - 指针比较使我的程序崩溃

c - 我如何知道当前持有的是哪种类型(int、double、float 等)?