我的数组长度为什么突然无明显原因而改变?

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

Why did my array length suddenly change with no apparent reason?

问题

printf("m=%d,M=%d,float_size=%d\n", m, M, floatsize);
a = (float*)malloc(floatsize * m * M);
f = (float*)malloc(floatsize * M);
printf("bytes of a is %d, bytes of f is %d\n", sizeof(a), sizeof(f));
The result is:

m=1,M=3,float_size=4
bytes of a is 8, bytes of f is 8
As screenshot shown below:

我的数组长度为什么突然无明显原因而改变?

Shouldn't it be 3*4=12 instead of 8? How come?

英文:
printf("m=%d,M=%d,float_size=%d\n", m, M, floatsize);
a = (float*)malloc(floatsize * m * M);
f = (float*)malloc(floatsize * M);
printf("bytes of a is %d, bytes of f is %d\n", sizeof(a), sizeof(f));

The result is:

m=1,M=3,float_size=4
bytes of a is 8, bytes of f is 8

As screenshot shown below:

我的数组长度为什么突然无明显原因而改变?

Shouldn't it be 3*4=12 instead of 8? How come?

答案1

得分: 1

af不是数组,它们是指向通过malloc(3)分配的内存的指针。

对指针使用sizeof返回的是指针的大小,在您的情况下似乎是8字节,而不是指向的数据的大小。

另外:对malloc(3)系列函数的返回进行强制转换是多余的,只会使代码变得混乱。这些函数返回一个通用的void *,会被隐式转换为任何其他指针类型。(在C语言没有void *之前,需要进行强制转换,因为这些函数返回的是char *

英文:

a and f are not arrays, they're pointers that are pointing to the memory allocated through malloc(3).

sizeof on a pointer returns the size of the pointer — which in your case seems to be 8 bytes — not the pointed-to data.

Aside: Casting the return of malloc(3) family is redundant and only serves to clutter one's code. These functions return a generic void * that is implicitly converted to any other pointer type. (The cast was required when C didn't have a void *, and these functions returned a char *)

huangapple
  • 本文由 发表于 2023年3月31日 22:18:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899595.html
匿名

发表评论

匿名网友

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

确定