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.

3
  • 6
    Don't cast the result of malloc (and friends). Commented Oct 30, 2014 at 15:54
  • 4
    The first array is not an array, but a pointer to elements of type int. The second one is! Commented Oct 30, 2014 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. Commented Oct 30, 2014 at 15:56

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.