malloc1
Copy the following program into malloc1.c. Study the program carefully before you compile and run it. Then run the program and make sure you can see why each line of output is generated.
#include <stdio.h> #include <stdlib.h> /* needed to use malloc and free */ main() { int *p1; /* address of 1st integer */ int *p2; /* address of 2nd integer */ p1 = (int *) malloc(sizeof(int)); /* allocate space for 1st integer */ printf("p1 allocated memory at address %p\n",p1); p2 = (int *) malloc(sizeof(int)); /* allocate space for 2nd integer */ printf("p2 allocated memory at address %p\n",p2); printf("1st no? "); scanf(" %i",p1); /* store input as 'value at address p1' */ printf("2nd no? "); scanf(" %i",p2); /* store input as 'value at address p2' */ printf("sum of %d and %d is %d\n",*p1,*p2,*p1+*p2); /* print 'value at address p1', 'value at address p2' and * 'value at address p1' plus 'value at address p2' */ free(p1); /* free up dynamic memory at address p1 */ free(p2); /* free up dynamic memory at address p1 */ }
Look closely at the scanf statements. Why is it correct to write p1
and not &p1
(and similar argument for p2
)?