Solution for Exercise 05_03-sizes.c
05_03-sizes.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
double *d;
/* allocate storage for 100 double values */
d = malloc( sizeof(double) * 100 );
/* always test the result */
if( d==NULL )
{
fprintf(stderr,"Unable to allocate memory\n");
exit(1);
}
/* output data */
printf("The buffer's address is %p\n",d);
printf("The buffer's size is %zu bytes\n",sizeof(double)*100 );
/* clean-up */
free(d);
return 0;
}
Output
The buffer's address is 0x55bbbce832a0
The buffer's size is 800 bytes
Notes
* Based on the output, a double on this system occupies 8 bytes of storage.
* Yes, the address you see when you run the program will doubtless be different from what's shown above.
* Pointer variable d is declared as a double. It's assigned an address from the malloc() function equal to the size of a double multiplied to 100. This quantity ensures enough storage for 100 double values.
* An if test confirms that the buffer is properly allocated. If not, the program exits.
* The two printf() statements output the results as requested in the book: The buffer's address and the buffer's size.
* The %p placeholder is used to output an address.
* The %zu placeholder is used to output a size_t value, the number of bytes in a buffer.
* The buffer's size is calculated by using the same expression found the malloc() statement: sizeof(double)*100. the result is the exact number of bytes required to store 100 double values in memory.
* As usual, your solution need not look exactly like mine.
Copyright © 1997-2025 by QPBC.
All rights reserved
