简体   繁体   English

即使我没有提到数组的大小,为什么在编译和运行代码时仍能正常工作?

[英]Why does the code work fine when I compile and run it even though I have not mentioned size of array?

class array {
    public:
        int arr[];

        array() {
            arr[0] = 1;
            arr[100] = 2;
        }
};

int main() {
    array a;
    cout << a.arr[0] << a.arr[100] << endl;
    return 0;
}

I was expecting a segmentation fault on running the above code. 我在运行上面的代码时遇到分段错误。 However, it printed the correct output even though I have not mentioned array size. 但是,即使我没有提到数组大小,它也会打印正确的输出。 What is the reason for this? 这是什么原因呢?

What you get is Undefined Behavior. 您得到的是未定义行为。

Reading / Writing to unallocated memory does not automatically generate segmentation fault(s), but it is of course "bad practice" and should be avoided. 读/写未分配的内存不会自动生成分段错误,但是这当然是“不好的做法”,应避免使用。

It's impossible to tell exactly what will happen with such code, where that array will be addressed or what is already there and hence - Undefined Behavior. 无法确切说明此类代码将发生什么,该数组将在何处寻址或已经存在什么,因此-未定义行为。

Note : As mentioned by @juanchopanza, the code as it is is illegal in C++ because arr is an incomplete type. 注意 :如@juanchopanza所述,由于arr是不完整的类型,因此该代码在C ++中是非法的。 Your compiler might (and obviously does) ignore this due to default settings, but a legal code that would demonstrate the same behavior is either: 您的编译器可能(并且显然确实)由于默认设置而忽略了这一点,但是可以证明相同行为的合法代码是:

class array {
    public:
        int *arr;
// ...

or 要么

class array {
    public:
        int arr[1];
// ...

暂无
暂无

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

相关问题 即使我有未定义的成员函数,为什么下面的代码也会编译? - Why does the following code compile even though I have undefined member functions? 为什么即使我没有为它分配内存也能工作? - Why does gets work even when I have not allocated memory to it? 当我将数组交换为向量时,为什么此代码不再起作用? - Why does this code no longer work when I swap the array for a vector? 为什么我得到数组绑定不是一个 integer 常量在 ']' 标记之前,即使全局声明了大小? - Why am I getting array bound is not an integer constant before ‘]’ token even though declared the size globally? 为什么即使我在项目设置中更改了语言标准,std::lcm() 也不起作用? - Why does std::lcm() not work even though I changed the language standard in project settings? 即使我有头文件,代码输入错误 - Error with input in code even though i have the header file 当我连接调试器/ IDE时,为什么我的STL代码运行得如此之慢? - Why does my STL code run so slowly when I have the debugger/IDE attached? 为什么在向向量添加元素时向量具有相同的大小? - Why does a vector have the same size when I add elements to it? 为什么到目前为止,我在Codechef的Faded Palindromes中都获得了WA,即使到目前为止我的代码中都没有发现错误,并且对我来说也可以正常工作? - Why am I getting a WA in Faded Palindromes in Codechef even though I found no error till now in my code and its working fine for me? 为什么下面的代码没有崩溃,虽然我已经删除了 object? - Why the below piece of code is not crashing , though i have deleted the object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM