英文:
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
a
和f
不是数组,它们是指向通过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 *
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论