直接指向 C 中的文本不是不可能吗?
Shouldn't it be impossible to point directly to text in C?
我正在学习 C,我遇到了指针。
尽管我从本教程中学到的知识比从教科书中学到的更多,但我仍然对字符指针感到疑惑。
如果我编程这个
#include <stdio.h>
int main()
{
char *ptr_str;
ptr_str = "Hello World";
printf(ptr_str);
return 0;
}
结果是
Hello World
我不明白为什么编译时没有错误,因为指针 ptr_str 直接指向文本而不是文本的第一个字符。我以为只有这个行得通
#include <stdio.h>
int main()
{
char *ptr_str;
char var_str[] = "Hello World";
ptr_str = var_str;
printf(ptr_str);
return 0;
}
所以在第一个示例中,我是如何直接指向文本的?
您的代码有效,因为字符串文字本质上是静态数组。
ptr_str = "Hello World";
被编译器视为
static char __tmp_0[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '[=11=]' };
ptr_str = __tmp_0;
(除非尝试修改字符串文字的内容具有未定义的行为)。
您甚至可以将 sizeof
应用于字符串文字,您将获得数组的大小:例如,sizeof "Hello"
为 6。
在赋值给 char 指针的上下文中,字符串文字的 'value' 是其第一个字符的地址。
所以
ptr_str = "Hello World";
将 ptr_str 设置为 'H'
的地址
为什么第一个不起作用?它会像您看到的那样工作。
字符串文字是数组。来自 §6.4.5p6 C11
标准 N1570
The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence.
现在在第一种情况下 literal array decayed into pointer to first element - 所以衰减指针基本上会指向 'H'
。您将该指针分配给 ptr_str
。现在 printf
将需要一个格式说明符和相应的参数。这里它将是 %s
,相应的参数将是 char*
。 printf
将打印每个字符,直到到达 [=18=]
。事情就是这样。这就是您如何最终 直接指向文本 。
请注意,第二种情况与第一种情况完全不同——第二种情况正在制作可以修改的副本(尝试修改第一种情况将是未定义的行为)。我们是 basically initializing a char
array 字符串文字的内容。
我正在学习 C,我遇到了指针。 尽管我从本教程中学到的知识比从教科书中学到的更多,但我仍然对字符指针感到疑惑。
如果我编程这个
#include <stdio.h>
int main()
{
char *ptr_str;
ptr_str = "Hello World";
printf(ptr_str);
return 0;
}
结果是
Hello World
我不明白为什么编译时没有错误,因为指针 ptr_str 直接指向文本而不是文本的第一个字符。我以为只有这个行得通
#include <stdio.h>
int main()
{
char *ptr_str;
char var_str[] = "Hello World";
ptr_str = var_str;
printf(ptr_str);
return 0;
}
所以在第一个示例中,我是如何直接指向文本的?
您的代码有效,因为字符串文字本质上是静态数组。
ptr_str = "Hello World";
被编译器视为
static char __tmp_0[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '[=11=]' };
ptr_str = __tmp_0;
(除非尝试修改字符串文字的内容具有未定义的行为)。
您甚至可以将 sizeof
应用于字符串文字,您将获得数组的大小:例如,sizeof "Hello"
为 6。
在赋值给 char 指针的上下文中,字符串文字的 'value' 是其第一个字符的地址。
所以
ptr_str = "Hello World";
将 ptr_str 设置为 'H'
的地址为什么第一个不起作用?它会像您看到的那样工作。
字符串文字是数组。来自 §6.4.5p6 C11
标准 N1570
The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence.
现在在第一种情况下 literal array decayed into pointer to first element - 所以衰减指针基本上会指向 'H'
。您将该指针分配给 ptr_str
。现在 printf
将需要一个格式说明符和相应的参数。这里它将是 %s
,相应的参数将是 char*
。 printf
将打印每个字符,直到到达 [=18=]
。事情就是这样。这就是您如何最终 直接指向文本 。
请注意,第二种情况与第一种情况完全不同——第二种情况正在制作可以修改的副本(尝试修改第一种情况将是未定义的行为)。我们是 basically initializing a char
array 字符串文字的内容。