gpt4 book ai didi

c++ - 为什么 C++ 变量是指针时不需要正确定义?

转载 作者:太空狗 更新时间:2023-10-29 19:37:24 24 4
gpt4 key购买 nike

我是 C++ 语言的新手(尤其是指针,经验主要是 PHP),希望对以下内容有一些解释(我已经尝试寻找答案)。

两行代码如何能够在我的程序中完成完全相同的工作?第二行似乎违背了我到目前为止所学和理解的关于指针的一切。

char disk[3] = "D:";

char* disk = "D:";

我怎样才能初始化指向内存地址以外的任何指针?不仅如此,在第二行我也没有正确声明数组 - 但它仍然有效?

最佳答案

在 C 和 C++ 中初始化数组的常用方法是:

int a[3] = { 0, 1, 2 };
Aside: And you can optionally leave out the array bound and have it deduced from the initializer list, or have a larger bound than there are initializers:
int aa[] = { 0, 1, 2 };    // another array of three intsint aaa[5] = { 0, 1, 2 };  // equivalent to { 0, 1, 2, 0, 0}

对于字符数组,有一个特殊规则允许从字符串文字初始化数组,数组的每个元素都从字符串文字中的相应字符初始化。

您的第一个示例使用字符串文字 "D:" 因此数组的每个元素都将初始化为该字符串中的一个字符,相当于:

char disk[3] = { 'D', ':', '\0' };

(第三个字符是 null terminator ,它隐式存在于所有字符串文字中)。

Aside: Here too you can optionally leave out the array bound and have it deduced from the string literal, or have a larger bound than the string length:
char dd[] = "D:";    // another array of three charschar ddd[5] = "D:";  // equivalent to { 'D', ':', '\0', '\0', '\0'}
Just like the aaa example above, the extra elements in ddd that don't have a corresponding character in the string will be zero-initialized.

您的第二个示例有效,因为字符串文字 "D:" 将由编译器输出并作为三个字符的数组存储在可执行文件的某处。当可执行文件运行时,包含数组(和其他常量)的段将被映射到进程的地址空间。因此,您的 char* 指针随后被初始化为指向该数组的位置,无论它恰好在哪里。从概念上讲,它类似于:

const char __some_array_created_by_the_compiler[3] = "D:";
const char* disk = __some_array_created_by_the_compiler;

由于历史原因(主要是 const 在 C 的早期不存在)使用非常量 char* 来指向它是合法的数组,即使数组实际上是只读的,所以 C 和第一个 C++ 标准允许您使用非常量 char* 指针来指向字符串文字,即使数组是它指的是真正的常量:

const char __some_array_created_by_the_compiler[3] = "D:";
char* disk = (char*)__some_array_created_by_the_compiler;

这意味着尽管出现你的两个例子并不完全相同,因为这只允许第一个:

disk[0] = 'C';

对于第一个没问题的例子,它改变了数组的第一个元素。

对于第二个示例,它可能会编译,但会导致 undefined behaviour ,因为它实际做的是修改 __some_array_created_by_the_compiler 的第一个元素,它是只读的。在实践中,可能会发生的情况是进程会崩溃,因为尝试写入只读内存页会引发段错误。

重要的是要了解 C++ 中有很多东西(C 中甚至更多)编译器可以愉快地编译,但是在执行代码时会导致非常糟糕的事情发生。

关于c++ - 为什么 C++ 变量是指针时不需要正确定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32233627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com