In: Computer Science
Create C program that takes 1 parameter: a number.
Using that number, dynamically allocate a memory so you store that number of integers.
Write integers in order starting from 1 until you fill all that memory.
Print the addresses and values of the first and the last integer stored in the memory.
Help ASAP!!!
Hi,
Hope you are doing fine. I have coded the above question in C keeping all the conditions in mind. Since a sample output of the code is not provided, I have taken the liberty to write it as per my convenience. You may modify it as per your requirement. The code has been clearly explained using comments that have been highlighted in bold.
Program:
#include<stdio.h>
#include<stdlib.h>
int main()
{
//declaring variables
//num is the input parameter, i is used for
indexing
int num,i=0;
//promptiong user for input
printf("Enter a number:\n");
scanf("%d",&num);
//declaring pointer that will hold the base
address of the dynamic memory block
int *arr;
//dynamically allocating memory of size num to
hold a list of integers. arr points to the base address of the
memory
arr=(int*)malloc(num * sizeof(int));
//filling the dynamically allocated
memory
for(i=0;i<num;i++)
{
arr[i]=i+1;
}
//printing the value of first
integer
printf("Value of first integer: %d\t",arr[0]);
//printing the address of first
integer
printf("Address: %d\n",&arr[0]);
//printing the value of last
integer
printf("Value of last integer:
%d\t",arr[num-1]);
//printing the address of last
integer
printf("Address: %d\n",&arr[num-1]);
}
Executable code snippet:
Output: