118k views
0 votes
Write two statements that each use malloc to allocate an int location for each pointer. Sample output for given program:

numPtr1 = 44, numPtr2 = 99
#include
#include
int main(void) {
int* numPtr1 = NULL;
int* numPtr2 = NULL;
/* Your solution goes here */
*numPtr1 = 44;
*numPtr2 = 99;
printf("numPtr1 = %d, numPtr2 = %d\\", *numPtr1, *numPtr2);
free(numPtr1);
free(numPtr2);
return 0;
}

User Kazuya
by
5.3k points

1 Answer

5 votes

Answer:

#include <stdio.h>

#include <stdlib.h>

int main(void) {

int* numPtr1 = NULL;

int* numPtr2 = NULL;

/* Your solution goes here */

numPtr1 = (int *) malloc(10);

numPtr2 = (int *) malloc(20);

*numPtr1 = 44;

*numPtr2 = 99;

printf("numPtr1 = %d, numPtr2 = %d\\", *numPtr1, *numPtr2);

free(numPtr1);

free(numPtr2);

return 0;

}

Step-by-step explanation:

The C library malloc function is used to assign memory locations (in bytes) to variables. It accepts the size parameter and returns a pointer to the specified variable location.

The two malloc statements above assign two memory locations 10 and 20 to the numPtr1 and numPtr2 integer variables respectively.

User Verity
by
6.5k points