简体   繁体   English

malloc 如何区分我分配一个 long long 整数和一个由两个整数组成的数组?

[英]How does malloc distinguish between me allocating a long long integer and an array of two integers?

in my OS long long int is : 8 bytes .在我的操作系统中 long long int 是:8 个字节。 int is 4 bytes . int 是 4 个字节。

int *p = malloc(4);

this code allocate 4 bytes for a variable of type integer on the heap .此代码为堆上的整数类型变量分配 4 个字节。

int *p = malloc(8);

will this allocate a long long integer like 'one variable' or two items on an array .这会分配一个长整数,如“一个变量”或数组上的两个项目。

how can i allocate an integer of 8 bytes long ?我如何分配一个 8 字节长的整数? how can i allocate an array containing 2 items ?我如何分配一个包含 2 个项目的数组?

malloc() just allocates raw memory, whether it's treated as an array or a single variable is determined by how the memory is used in the caller. malloc()只是分配原始内存,它是被视为数组还是单个变量取决于调用者如何使用内存。

int *p = malloc(2 * sizeof(int));

treats the memory as an array of 2 int .将内存视为 2 个int的数组。 You can then do:然后你可以这样做:

p[0] = 1;
p[1] = 2;

and it will write two int into the memory.它会将两个int写入内存。

long int *p = malloc(sizeof(long int));

treats the memory as a single long int (or, equivalently, an array of 1 long int ).将内存视为单个long int (或等效地,一个包含 1 个long int的数组)。 Then you can do:然后你可以这样做:

*p = 12345678;

and it will write that long integer into the memory.它会将那个长整数写入内存。

Both of them will allocate 8 bytes of memory on a system where int is 4 bytes and long int is 8 bytes.它们都将在int为 4 个字节且long int为 8 个字节的系统上分配 8 个字节的内存。

If you want an 8 byte integer, it's called a long long or int64_t / int64_t :如果你想要一个 8 字节的整数,它被称为long longint64_t / int64_t

If this is about C, then you use malloc :如果这是关于 C,那么你使用malloc

int64_t* p = malloc(sizeof(int64_t));

If this is about C++, then you use new :如果这是关于 C++,那么你使用new

int64_t* p = new int64_t;

With your original code you're getting an allocation of arbitrary size mapped to a pointer of a fixed size type , where int is typically 4 bytes, or in other words, you have room for int[2] .使用原始代码,您将获得映射到固定大小类型指针的任意大小的分配,其中int通常为 4 个字节,或者换句话说,您有空间容纳int[2]

Note: For portability reasons it's always best to express your allocations in terms of base types, not just abstract numbers.注意:出于可移植性的原因,最好根据基本类型来表达您的分配,而不仅仅是抽象数字。 malloc(8) may allocate memory for 2 x int , or it may not, that depends on what sizeof(int) is. malloc(8)可能会为 2 x int分配内存,也可能不会,这取决于sizeof(int)是什么。 malloc(sizeof(int) * 2) always works correctly. malloc(sizeof(int) * 2)始终正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM