到目前为止我了解到以下声明:
char *ch
声明一个指针,如果我们想将此指针连接到任何地址,我们必须将其写为:
char *c = &n
,但是我无法理解以下程序的含义,
#include <stdio.h>
int main()
{
char *ch = "Hello World" ;
printf("%s", ch) ;
return 0 ;
}
请解释一下第 2 行分配部分背后的逻辑以及为什么要打印 Hello world。
不应该用 *ch 代替 printf 中的 ch 吗?
最佳答案
根据 C 标准(6.3.2.1 左值、数组和函数指示符)
3 Except when it is the operand of the sizeof 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. If the array object has register storage class, the behavior is undefined.
因此在此声明中
char *ch = "Hello World";
右侧有一个字 rune 字,其类型为以下数组char[12]
(字 rune 字包括终止零“\0”)
根据引用,该数组被转换为一个表达式,该表达式是指向数组第一个字符(字符串文字)的指针。因此指针ch
由数组第一个字符的地址初始化。文字本身由编译器存储在静态内存中的某个位置。
事实上,在这个语句中,您定义了两个对象:一个字符数组(字符串文字)和一个指向字符串文字第一个字符的指针。
虽然 C 中的字符串文字不是常量数组,但您不能使用此类指针更改它们。任何更改字符串文字的尝试都会导致程序的未定义行为。
至于这个说法
printf("%s", ch) ;
然后当ch
指向字符串的第一个字符时,则根据格式说明符%s
输出该字符串
关于c - 我该如何解释这个声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31085989/