c++ - 在分配的数组之外添加项目?

标签 c++ arrays

我有一个类集:

class Set
{
public:
    //Default constructor
    Set ();

    //Some more functions...

private:
    int *p;
    const int K = 10;
    int numval = 0; //Number of ints in the array

    //Other variables...
};

默认构造函数:

Set::Set()
{
    p = new int[K]; //Allocate memory for array with 10 ints
}

如果我在其他某个函数中用 10 个整数填充数组,然后添加另一个整数,会发生什么?编译器不会崩溃,我可以打印第 11 个整数。但是因为我没有为它分配内存,它存储在哪里?

例子:

Set1 += 5;

将使用以下运算符重载器将 5 添加到数组。

const Set& Set::operator+=(const int x)
{
    p[numval] = x; //Add next int after the last int in the array
    numval++; //Increment number of ints
    return *this;
}

最佳答案

If I in some other function would fill the array with 10 ints and then add an other one, what would happen?

你会写入数组末尾之后的任何内存,导致未定义的行为:可能不会导致明显的问题,可能会破坏一些不相关的数据(或用于管理堆的元数据),或者如果有的话可能会崩溃那里没有可写内存。

But since I havn't allocated memory for it, where is it stored?

从为它分配存储的意义上说,它没有存储在任何地方。没有什么可以阻止您写入数组末尾以外的任意内存位置。小心不要那样做。

关于c++ - 在分配的数组之外添加项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27201730/

相关文章:

ios - String 到 UIColor 的字典数组

arrays - 如何在 swift 3 中显示 UITextField 中的数组元素?

c++ - 静态初始化不使用 _initterm 而是使用 _Init_thread_header()/footer()

c++ - 在 header 中使用未命名的 namespace 会如何导致 ODR 违规?

c++ - 在 iPhone 上使用开罗?

c# - 检查 boolean 数组中的元素值 - C#

javascript - 按标签重构嵌套 JSON 数据 - Javascript

c++ - 如何获取哈希值,c++ hash_map

c++ - vc++ 中 std::string/std::wstring 的宏是什么?

Java从property.file中填充int [] []数组