2

I have created an array using malloc with the following line of code:

 int* array = (int*)malloc(12*sizeof(int));

I attempt to get the size with:

int size = sizeof(array)/sizeof(int);

This returns 2 however, not 12 (I'm aware that sizeof(array[0] is more general.) Confusingly (for me), when I create an array using

int array[12] 

the above line of code returns the correct size: 12.

Further, I'm able to fill the int* array with 12 integers without a segmentation fault, which I don't understand if the size turns out to be 2.

Could someone please tell me what I'm doing wrong / how to get the size of an array initialized using malloc in c?

Sorry if this is basic I looked around and couldn't find an answer.

Thanks for your time.

dinosaurW
  • 113
  • 2
  • 10
  • 6
    [Don't cast the result of malloc (and friends)](http://stackoverflow.com/q/605845). – Deduplicator Oct 30 '14 at 15:54
  • 4
    The first `array` is not an array, but a pointer to elements of type `int`. The second one is! – Deduplicator Oct 30 '14 at 15:55
  • 3
    There's more than likely a duplicate somewhere, but the general answer is `sizeof(array)` in the first case gives you the size of the pointer, *not* the size of the array; there's no way to determine the size of an array from just a pointer. – Drew McGowen Oct 30 '14 at 15:56

1 Answers1

1
int *arr = malloc(sizeof(int));

No need to cast malloc(). arr is a pointer so in the first case you are using the

sizeof(arr)

which gives you the size of pointer not the size of the array.

In the second case you have a array

int arr[12];

Here you get the size of your array arr which is

sizeof(arr)/sizeof(int)
Gopi
  • 19,784
  • 4
  • 24
  • 36