我刚开始学习 C++,遇到了一个在 Internet 上找不到的问题,希望您能帮助我。
这是我的代码:
int* a;
int* b;
a = (int*)calloc(1, sizeof(int));
b = (int*)calloc(5, sizeof(int));
cout << sizeof(a) << endl;
cout << sizeof(b) << endl;
编译器返回给我的是:8、8。 如果我使用:
cout << sizeof(*a) << endl;
cout << sizeof(*b) << endl;
编译器返回 4, 4。
malloc 也是一样。我正在使用。
我做错了什么?为什么 b 的大小不是 20,因为如果 int 是 4 个字节长,它会大 5 倍?
谢谢!
最佳答案
sizeof(*a)
和 sizeof(*b)
总是等于 4。您似乎希望它们返回数组的大小,但您需要了解 a
和 b
是不是数组。它们是指向 int
的指针.如果sizeof(int)
是 4,那么 sizeof(*a)
也将是 4,这在编译时就已经知道了。
话虽如此,您不需要使用 C 库函数 malloc()
和 calloc()
在 C++ 中。如果需要手动分配内存,请使用 new
和 delete
:
a = new int;
b = new int[5];
如果你需要像calloc
那样做零初始化确实,只需使用 ()
默认构造分配的整数:
a = new int();
b = new int[5]();
而不是 free()
, 使用 delete
或 delete[]
, 取决于如何 new
之前被称为:
delete a; // Note: no '[]'
delete[] b; // Needs '[]'
但是,您不需要在这里手动分配内存。只需使用 std::vector<int>
:
#include <vector>
// ...
std::vector<int> a(5); // 5 int elements, zero-initialized.
std::cout << a.size() << '\n'; // Will print '5'.
根据经验,您的 C++ 代码不应调用任何 new
, delete
, malloc()
, calloc()
或 free()
.进行手动内存管理需要更多代码并且容易出错。使用类似 vector
的容器和智能指针,如 shared_ptr
和 unique_ptr
相反,以减少内存和其他资源泄漏的机会。这些更安全的类型也更方便。与 vector
例如,您不必自己记住分配的内存大小。 vector
为您跟踪它的大小。您还可以通过直接分配 vector 来轻松复制 vector 。你也不需要 delete
或 free()
手动 vector 。当它们超出范围时,它们会被自动删除。
作为旁注,我建议改掉使用 endl
的习惯。用于打印换行符。 endl
刷新流,它不只是打印换行符。如果你使用它,你将不断地刷新输出流,这是一个缓慢的操作。您很少需要刷新流,在这种情况下,您可以使用 << flush
手动执行此操作。如果有需要。
关于C++ 编程,动态内存不能正常使用 malloc 和 calloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56194120/