gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:01:29 25 4
gpt4 key购买 nike

我有一个类集:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com