简体   繁体   English

关于双指针的澄清 - 无法解释行为

[英]clarification about double pointers - cannot explain the behavior

while preparing to the end of semester exam I have stumbled upon the following question: Given this piece of code:在准备期末考试时,我偶然发现了以下问题:鉴于这段代码:

#include <stdio.h>

int main() {

    const char *const ptr1[] = {"to be", "or not to be", "that is the question"};
    char *ptr2 = "that is the question";

    (&ptr2)[3]="hamlet";
    for (int i = 0; i < sizeof(ptr1) / sizeof(*ptr1); ++i)
        printf("%s ", ptr1[i]);
    return 0;
}

prints the following: "to be hamlet that is the question"打印以下内容:“成为小村庄就是问题”

I thought that this code wouldn't compile.我认为这段代码不会编译。

However, the code compiles.但是,代码可以编译。

can someone please help me understand why does this code behave like that?有人可以帮我理解为什么这段代码会这样吗?

It will probably compile, since there is nothing in the code that would require the compiler to diagnose a problem.它可能会编译,因为代码中没有任何内容需要编译器来诊断问题。

The assignment works in the sense that the types are correct.分配在类型正确的意义上起作用。 ptr2 has type char* , so &ptr2 has type char** and (&ptr2)[3] has type char* , which we can assign a string literal. ptr2char*类型,所以&ptr2char**类型, (&ptr2)[3]char*类型,我们可以分配一个字符串文字。

However, ptr2 is not an array, so accessing it at offset 3 is not possible.但是, ptr2不是数组,因此无法在偏移量3处访问它。 The program has undefined behavior and it doesn't make sense to claim a specific output.该程序具有未定义的行为,因此声明特定的 output 是没有意义的。

Enable warnings and sanitizers when compiling the program and see what is wrong: https://godbolt.org/z/G67j6qr7a编译程序时启用警告和清理程序,看看有什么问题: https://godbolt.org/z/G67j6qr7a

The code compiles, the assignment itself is valid as far as C language syntax and constraints go.代码编译,赋值本身就 C 语言语法和约束 go 有效。 However, it invokes undefined behavior (see What is undefined behavior and how does it work? ) since you access the variable ptr2 out of bounds - which is nonsense.但是,它会调用未定义的行为(请参阅什么是未定义的行为以及它是如何工作的? ),因为您越界访问变量ptr2 - 这是无稽之谈。 I don't get that output which you claim on my compiler, simply because there is no deterministic outcome from this code.我没有得到你在我的编译器上声称的 output,只是因为这段代码没有确定性的结果。

On some systems the out of bounds access might generate an access of the previously declared array on the stack, but there are no guarantees of such behavior.在某些系统上,越界访问可能会生成对堆栈上先前声明的数组的访问,但不能保证这种行为。 Most systems have down-counting stacks, so I don't think a lot of them would end up modifying the pointer array as assumed.大多数系统都有向下计数的堆栈,所以我认为它们中的很多最终不会像假设的那样修改指针数组。 In addition the compiler is free to allocate ptr1 and ptr2 at any addresses in relation to each other.此外,编译器可以自由地在彼此相关的任何地址分配ptr1ptr2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM