0
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:

weird array length

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

Harith
  • 4,663
  • 1
  • 5
  • 20
  • 3
    a and f are not arrays. They are pointers. So the expressions sizeof(a) and sizeof(f) yield sizes of pointers. Also pay attention that to output values of the type size_t you have to use the conversion %zu instead of %d. – Vlad from Moscow Mar 31 '23 at 14:20
  • 1
    Typically you do not cast `malloc` in C. That said, show the definitions for `floatsize` and `a`/`f` (the latter I assume to be `float*`). You're getting the size of the pointers, and it's not impossible that the size of a `float` on your machine is 8 bytes (or some weird argument promotion is happening). – Rogue Mar 31 '23 at 14:21
  • 1
    Does this answer your question? [Why the size of pointer to array is always 8 in C?](https://stackoverflow.com/questions/27986044/why-the-size-of-pointer-to-array-is-always-8-in-c) – ChrisB Mar 31 '23 at 14:24

1 Answers1

1

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 *)

Harith
  • 4,663
  • 1
  • 5
  • 20