本文介绍了在C ++中使用new和delete的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在了解何时应使用以下选项时需要帮助

I need help in understanding when shall I use the following options

char *a = new char();

char *a = new char[sizeof(int)+1];

以及如何进行相应的内存释放调用?

and how the respective memory freeing calls should be made?

推荐答案

第一个分配一个char。您可以使用以下命令删除它:

The fist one allocates a single char. You delete it with:

delete a;

第二个分配一个字符数组。您选择的长度有些奇怪。您可以使用以下命令取消分配它:

The second one allocates an array of chars. The length you have chosen is a little strange. You deallocate it with:

delete[] a;

现在...我希望您不要在第二个字符串中加上字符串化的数字 a (类似于 123456 ,因为您将需要更多的字节。如果 int 是32位。有一个有趣的公式可以计算所需的最小长度。它近似为log10

Now... I hope you don't think you can put a stringified number in the second a (something like "123456", because you'll need many more bytes. Let's say at least 12 if an int is 32 bits. There is a funny formula to calculate the minimum length necessary. It's an approximation of the log10 https://stackoverflow.com/a/2338397/613130

要清楚,在我的机器上 sizeof(int) == 4,但是在 int 中,我可以放置 -2147483648 这是10位数字加上-,所以11(加上零终止符)

To be clear, on my machine sizeof(int) == 4, but in an int I can put -2147483648 that is 10 digits plus the -, so 11 (plus the zero terminator)

这篇关于在C ++中使用new和delete的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 06:56