这两者之间有任何区别吗?

huangapple go评论85阅读模式
英文:

Is there any difference between these two?

问题

我不知道这是否可能,但我感到困惑。
它们是否相同?
我知道在第一种情况下,我们动态分配了20个int类型元素的内存。

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

p=(int *) malloc(sizeof(int)*20);
英文:

I donno if this is possible or not but am confused.
Are they both same?
I know that in the first case we are allocating memory dynamically for 20 elements of type int.

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

and

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

答案1

得分: 2

请注意,sizeof 操作符返回类型:size_t

int * size_t (20*sizeof(int)) 与 size_t * int (sizeof(int) * 20) 的情况下:乘积与较窄的类型首先扩展到另一个类型,而在C中乘法是_可交换的_:a*b 等于 b*a

情况会发生变化,当涉及 int * int * size_tsize_t * int * int 时,因为在C中,乘法不是_结合的_。首先会进行 int * int(产生 int 乘积),然后再进行 int * size_t。对于某些特定值,第一次乘法可能会溢出,而 size_t * int * int 则不会。

当有多个对象需要相乘时,最好确保最宽的乘法首先进行,例如 size_t * int * int


> 这两者之间有什么区别吗?

只有两个对象要相乘时,可以根据自己的喜好编写代码。
我喜欢以可能更宽的类型开始。


由于不需要进行强制类型转换,并且根据对象的大小来编写代码更容易进行正确的编码、审查和维护,请考虑以下方式:

p = malloc(sizeof p[0] * 20);
if (p == NULL) {
  TBD(); // 处理内存不足情况
}
英文:

Recall that sizeof operator returns type: size_t.

In the case of int * size_t (20*sizeof(int)) versus size_t * int (sizeof(int) * 20): the product is the same as the narrower type is widened to the other first and multiplication in C is commutative: a*b equals b*a.

The situation changes with int * int * size_t versus size_t * int * int as in C, multiplication is not associative. The first multiples int * int (with an int product), then does int * size_t. With select values, the first multiplication may overflow whereas size_t * int * int does not.

When more than 2 objects may be multiplied, best to make certain the widest multiplication happens first and subsequently: example size_t * int * int.


> Is there any difference between these two?

With only 2 objects to multiply, code in whatever way you like.
I like to lead with the likely wider type.


Since the cast is not needed and sizing to the object is easier to code right, review and maintain, consider:

p = malloc(sizeof p[0] * 20);
if (p == NULL) {
  TBD(); // Handle out-of-memory
}

huangapple
  • 本文由 发表于 2023年7月3日 12:27:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601840.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定