I'm relatively new to C, and I've been messing around with pointers to an int array to help solidify my understanding. Here is some code I typed up that confused me:
#include <stdio.h>
int main(int argc, char **argv)
{
int sizeOfInt = sizeof (int);
printf("The size of an int is %d \n",sizeOfInt);
int StaticArray[10];
int staticSize = sizeof(StaticArray);
printf("The size of the static array with 10 elements, all unused, is %d\n\n", staticSize);
int *DynamicArray = malloc( 10 * sizeof(int) );
printf("The dynamic array *DynamicArray has been allocated 10 int elements worth of memory\n");
int sizeOfDynamic = sizeof(DynamicArray);
printf("Since none of those elements have been assigned an int yet, the array currently takes up %d memory\n\n", sizeOfDynamic);
*DynamicArray = 10;
printf("The first element, at address %x , is %d \n",DynamicArray, *DynamicArray); //DynamicArray refers to address of start of array
printf("The address of the pointer *DynamicArray is %x \n",&DynamicArray); //&DynamicArray refers to address of pointer
DynamicArray[1] = 20;
printf("The second element, at address %x , is %d \n",DynamicArray, DynamicArray[1]); //DynamicArray refers to address of start of array
sizeOfDynamic = sizeof(DynamicArray);
printf("The size of the array after assigning 2 int elements is now %d", sizeOfDynamic);
//Free unused memory
free(DynamicArray);
return 0;
}
When I run this program, I get the following output:
The size of an int is 4
The size of the static array with 10 elements, all unused, is 40
The dynamic array *DynamicArray has been allocated 10 int elements worth of memory
Since none of those elements have been assigned an int yet, the array currently takes up 8 memory
The first element, at address 1f69b0 , is 10
The address of the pointer *DynamicArray is 62fe08
The second element, at address 1f69b0 , is 20
The size of the array after assigning 2 int elements is now 8
Why is it that before assigning any elements to *DynamicArray, its size is 8?
Since *DynamicArray had a size of 8 to begin with, how does it still only have a size of 8 after assigning two elements to it?
If I allocated 10 int elements worth of memory for *DynamicArray, it is initially as wasteful of memory as a static array of 10 elements until I call free(DynamicArray), correct?
Thank you for any clarification!