-2

I am simply trying to dynamically declare an array in C The code is as follows:

int maxSize = 3;
int *answer;
answer = malloc(maxSize * sizeof(int));
printf("this is max size: %d\n", maxSize);
printf("this is the mult result: %d\n", maxSize * sizeof(int));
printf("size of answer in bytes: %d\n", sizeof(answer));
printf("size of the answer array: %d\n", sizeof(answer) / sizeof(answer[0]));

Printing the result gives me:

this is max size: 3
this is the mult result: 12
size of answer in bytes: 8
size of the answer array: 2

I don't think it's an architecture thing (rather me being inexperienced), but I am running this on a Macbook Pro.

I do not understand why is malloc only allocating 8 bytes instead of 12 bytes for the integer array.

FSB
  • 49
  • 1
  • 10

1 Answers1

1

Sizeof(answer) is returning the size of the variable answer in memory, which is the same as sizeOf(int *). Since your computer architecture is 64-bit, the size of a pointer is 8 bytes, which is your result. Your computer is indeed allocating 12 bytes, but you don't really have a way to validate that.

matanso
  • 1,284
  • 1
  • 10
  • 17
  • Thank you. This means the C compiler doesn't have knowledge of dynamically allocated memory and you can't use functions to keep track of the memory allocated, correct? – FSB Mar 15 '16 at 18:07
  • Yes, you're absolutely correct. – matanso Mar 15 '16 at 18:08