简体   繁体   English

使用unsigned long long int进行动态分配

[英]Using unsigned long long int for dynamic allocation

If I have the following variable unsigned long long int *size , is it a good practice to leave size = calloc(2, sizeof(int)) or it should be size = calloc(2, sizeof(unsigned long long int)) ? 如果我具有以下变量unsigned long long int *size ,则保留size = calloc(2, sizeof(int))还是一个好习惯,还是应该将其设置为size = calloc(2, sizeof(unsigned long long int))

Thank you 谢谢

Second option. 第二种选择。 You don't want to make assumptions about datatype sizes in c. 您不想对c中的数据类型大小进行假设。
It is very platform/compiler dependent. 这是非常依赖于平台/编译器的。

There is no reason to assume that int and unsigned long long int are the same size (they may be). 没有理由假定intunsigned long long int的大小相同(可能是相同的)。 If size is declared as unsigned long long int , then of the two options presented, the correct choice is: 如果将size声明为unsigned long long int ,则在显示的两个选项中,正确的选择是:

size = calloc(2, sizeof(unsigned long long int));

A better practice is to avoid using explicit types with sizeof : 更好的做法是避免使用带有sizeof显式类型:

size = calloc(2, sizeof *size);

This is less error-prone in the initial coding, and more maintainable. 这在初始编码中不太容易出错,并且更易于维护。 If types change during the lifetime of the code, only the declaration needs to be changed here. 如果在代码有效期内更改类型,则仅需要在此处更改声明。

The size of int can be either 2 or 4 bytes, depending on the machine you run. 根据您运行的机器,int的大小可以为2或4个字节。
However, the size of unsigned long long is at least 8 bytes. 但是,无符号long long的大小至少为8个字节。

So no, it is NOT a good practice to use a worng size. 因此,不可以, 不要使用磨损的尺码。

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

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