#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]。我的问题是为什么每一次,都会是上面的那个结构体的输出为符合预期的值呢?
This is a common sense question:
Array subscripts in C/C++ start from 0, and
int a[sz];
defines thea[0]
elements froma[sz-1]
tosz
.Array access out of bounds is undefined behavior.
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 elementsa[1]~a[4]
. The accesses toa[3]
anda[4]
are out of bounds and are undefined. Behavior. Because you assigned an out-of-bounds value ofa[3]
to 4 during previous loop assignments (your compiler implements normal assignment, covering the contents of the memory wherea[3]
is located), but did not assign an out-of-bounds value toa[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.
int a[3] means the array length is 3...