0
typedef struct {
  double *x;
  int points;
} Polygon;



polygon[cc].points = readobject(polygon[cc].file); //lets say equals 15
polygon[cc].x = (double *) malloc(polygon[cc].points * sizeof(double));

printf("%d\n", sizeof(polygon[cc].x) / sizeof(polygon[cc].x[0]));
//This prints out on 1

I've test initializing x as x[100] and it works then, but shouldn't the malloc() call set the struct's array at x[15]? Is it just measuring the bytes of two doubles?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
af3ld
  • 782
  • 8
  • 30
  • What would you get with `polygon[cc].x[0]` ? x is not an array... – Claudio Nov 19 '15 at 10:36
  • 3
    Calling `sizeof` on dynamically allocated array would just return the size of pointer in bytes, not the size of whole array. – sgarizvi Nov 19 '15 at 10:36
  • `float x[15]` is a very different thing from `float *x = malloc(15 * sizeof(float))` Also, [don't cast the result of `malloc`](http://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc). – Nik Bougalis Nov 19 '15 at 10:45

2 Answers2

6

In your code

polygon[cc].x

is a pointer. by applying sizeof on that pointer, what you get is the size of that pointer itself, not the size of the allocated memory pointed by that pointer.

Remember, arrays are not pointers, so if you apply sizeof on an array, you'll get the size of the whole array.

In your case, sizeof(double *) is equal to sizeof(double), so you get the result as 1.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • If I want the want the size of the whole array, how would I go about calling that instead of a pointer? – af3ld Nov 19 '15 at 10:46
  • @af3ld As i mentioned, a pointer is not an array. If you allocate memory to a pointer and later you want to get the size of the allocated memory, you cannot get that info from that pointer. You may need to store the allocated size separately and pass that around. – Sourav Ghosh Nov 19 '15 at 11:13
  • 1
    Okay. Thanks for the help – af3ld Nov 19 '15 at 11:34
1

The type of polygon[cc].x is double *, the type of polygon[cc].x[0] is double.

It happens that on the computer you tested, pointers and doubles have the same size (8 bytes).

The operator sizeof doesn't know anything about the call to malloc() (it's none of its business); the sizeof expressions in the code you posted are evaluated at the compile time.

axiac
  • 68,258
  • 9
  • 99
  • 134