英文:
Why int allocates 8 bytes by default?
问题
在尝试在C++中分配内存时,默认情况下分配了8字节,而我预期分配4字节。
#include <iostream>
using namespace std;
int main(){
int* arr = new int;
cout << "arr " << sizeof(arr) << endl;
cout << "int16 " << sizeof(int16_t) << endl;
cout << "int32 " << sizeof(int32_t) << endl;
cout << "int64 " << sizeof(int64_t) << endl;
}
这是结果:
arr 8
int16 2
int32 4
int64 8
英文:
when I try to allocate memory in c++ it allocates 8 bytes by default I expected 4;
#include<iostream>
using namespace std;
int main(){
int* arr = new int;
cout << "arr " << sizeof(arr)<<endl;
cout << "int16 " << sizeof(int16_t)<<endl;
cout << "int32 " << sizeof(int32_t)<<endl;
cout << "int64 " << sizeof(int64_t)<<endl;
}
this is a result:
arr 8
int16 2
int32 4
int64 8
答案1
得分: 2
sizeof(arr)
是 int*
的大小。你很可能正在编译/执行 64 位架构,所以指针的大小为 8 字节。
sizeof(*arr)
的解引用打印出了预期的 int
大小,即 4
。
英文:
sizeof(arr)
is the size of the int*
. You're most likely compiling/executing for a 64bit architecture, so pointers are 8 bytes in size.
Dereferencing like sizeof(*arr)
prints the size of int
which is 4
as expected
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论