search

Home  >  Q&A  >  body text

c++ - CPP struct 的诡异问题


#include<iostream>
#include<cmath>
using namespace std;


struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};


int main()
{
    int a[3];
    for(int i=0;i<4;i++){
        a[i]=i+1;
    }

    ListNode*h = new ListNode(0);
    for(int i=0;i<4;i++){
        ListNode*t =new ListNode(a[i]);
        t->next = h->next;
        h->next = t;
        cout<<"t "<<i<<" "<<t->val<<endl;
    }

    ListNode*h2 = new ListNode(0);
    cout<<h2->val<<endl;
    for(int j=0;j<4;j++){
        ListNode*t2 =new ListNode(a[j]+1);
        t2->next = h2->next;
        h2->next = t2;
        cout<<"t2 "<<j<<" "<<t2->val<<endl;
    }
    return 0;
}

这段构建结构体的代码,错误在a[]的初始化,应该初始化4个,a[4]。我的问题是为什么每一次,都会是上面的那个结构体的输出为符合预期的值呢?

ringa_leeringa_lee2807 days ago577

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 13:31:32

    This is a common sense question:

    1. Array subscripts in C/C++ start from 0, and int a[sz]; defines the a[0] elements from a[sz-1] to sz.

    2. Array access out of bounds is undefined behavior.

    Why does the output of the above structure meet the expected value every time?

    It is related to the implementation of the compiler. Each compiler does not necessarily have the same implementation for undefined behavior. Your above structure stores the four elements a[0]~a[3], and the structure below stores the four elements a[1]~a[4]. The accesses to a[3] and a[4] are out of bounds and are undefined. Behavior. Because you assigned an out-of-bounds value of a[3] to 4 during previous loop assignments (your compiler implements normal assignment, covering the contents of the memory where a[3] is located), but did not assign an out-of-bounds value to a[4] (the unassigned built-in type local variable has The value is undefined, in other words, your compiler implements it as a random number), so the result in the screenshot appears.

    Undefined behavior should be prohibited during actual programming.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:31:32

    int a[3] means the array length is 3...

    reply
    0
  • Cancelreply