0

I would like to create a float array of 9 elements. Thus I made use of malloc primitve function to do so :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main(void){
  float* y;
  printf("sizeof(float)=%ld\n",sizeof(float));
  y = malloc (10*sizeof(float));
  printf("sizeof(y)=%ld\n", sizeof(y));
  float *x;
  x = (float *) malloc(9*sizeof(float));
  printf("sizeof(x)=%ld\n", sizeof(x));

}

The output is the following:

sizeof(float)=4
sizeof(y)=8
sizeof(x)=8

Therefore I am wondering why both sizeof(y) and sizeof(x) return 8. Shouldń't they return 10*sizeof(float)=10*4=40 and 9*sizeof(float)=9*4=36 respectively? Could someone please clarify to me why am I getting 8 instead for both arrays?

ecdhe
  • 421
  • 4
  • 17

1 Answers1

2

x and y are not declared as arrays. They are pointers to memory locations. Depending on the system, the pointers could be 8 bytes. That's what you're seeing.

If you were to declare an array int z[10], and did sizeof(z), you'd get 10*sizeof(int).

Kon
  • 4,023
  • 4
  • 24
  • 38