睿宏 陳
PRO
last week
睿宏country asked

If the ptr pointer holds the address of the first byte in the allocated memory, why do we need to allocate memory equal to "n*sizeof(double)" to ptr? double* ptr; int n = 100; // allocate memory of n number of double data ptr = (double*) malloc(n * sizeof(double));

Abhay Jajodia
Expert
last week
Abhay Jajodia answered

Good question! It’s essential to allocate the correct amount of memory for the data types we want to store.

When you use malloc(n * sizeof(double)), you're telling the program to allocate memory for n number of double values. Each double typically takes 8 bytes of memory. Therefore, by calculating n * sizeof(double), you're ensuring you get enough space for all the doubles you intend to store. If we only allocated ptr with an address without specifying the correct size, there might not be enough memory for all your doubles, leading to errors or program crashes.

So, we need to explicitly allocate n * sizeof(double) to ensure we have enough memory for all n double values you want to work with. Hope this helps!

C
This question was asked as part of the Learn C Programming course.