3i Infotech Placement: Sample Questions 1091 - 1091 of 1245
Glide to success with Doorsteptutor material for competitive exams : get questions, notes, tests, video lectures and more- for all subjects of your exam.
Question 1091
Describe in Detail Essay▾
How would you dynamically allocate a one-dimensional and two-dimensional arrays of integer?
EditExplanation
- We can create both statically and dynamically allocated array which can be both one-dimensional or multiple dimensional.
- Statically allocated have to specify size before compilation.
- However sometimes programmer doesn՚t know the size of the array ahead of time.
- Dynamically allocated array solve this problem by allocating space on heap at runtime.
- Provides library function to request heap memory at runtime.
One Dimensional (Dynamically Allocated)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char ⚹argv[])
{
int ⚹piBuffer =NULL;
int nBlock =0;
int iLoop =0;
printf("Enter the number of blocks =");
scanf("%d",&nBlock);
piBuffer =(int ⚹)malloc(nBlock ⚹sizeof(int));
if(piBuffer == NULL)
{
return 1;
}
for (iLoop =0 ; iLoop <nBlock ; iLoop++)
{
piBuffer[iLoop] =iLoop;
}
for (iLoop =0 ; iLoop <nBlock ; iLoop++)
{
printf("pcBuffer[%d] =%d", iLoop,piBuffer[iLoop]);
}
free(piBuffer);
return 0;
}
OUTPUT
Enter the number of block = 7
pcBuffer [0] = 0
pcBuffer [1] = 1
pcBuffer [2] = 2
pcBuffer [3] = 3
pcBuffer [4] = 4
pcBuffer [5] = 5
peBuffer [6] = 6
Two Dimensional Dynamically Allocated
#include<stdio.h>
#include <stdlib.h>
int main(int argc, char ⚹argv[])
{
int ⚹⚹piBuffer =NULL;
int nRow =0;
int nColumn =0;
int iRow =0;
int iCol =0;
printf("Enter the number of Row =");
scanf("%d",&nRow);
printf("Enter the number of Column =");
scanf("%d",&nColumn);
piBuffer =(int ⚹⚹)malloc(nRow ⚹sizeof(int⚹));
if(piBuffer == NULL)
{
return 1;
}
for (iRow =0 ; iRow <nRow ; iRow++)
{
piBuffer[iRow] =(int ⚹)malloc(nColumn ⚹sizeof(int));
if(piBuffer[iRow] == NULL)
{
return 1;
}
}
for (iRow =0 ; iRow <nRow ; iRow++)
{
for (iCol =0 ; iCol <nColumn ; iCol++)
{
piBuffer[iRow][iCol] =3;
}
}
for (iRow =0 ; iRow <nRow ; iRow++)
{
for (iCol =0 ; iCol <nColumn ; iCol++)
{
printf("piBuffer[%d][%d] =%d",iRow, iCol,piBuffer[iRow][iCol]);
}
}
for (iRow =0 ; iRow <nRow ; iRow++)
{
free(piBuffer[iRow]);
}
free(piBuffer);
return 0;
}
OUTPUT
Enter the number of Row = 2
Enter the number of column = 2
piBuffer [0] [0] = 3
piBuffer [0] [1] = 3
piBuffer [1] [0] = 3
piBuffer [1] [1] = 3