/* Function |insert| inserts block of ints |toInsert|, having |dim2| elements, i
ID: 3553953 • Letter: #
Question
/* Function |insert| inserts block of ints |toInsert|, having |dim2| elements, into the
// middle of block of ints |blk|, which has |dim1| elements. The inserted block starts at
// offset |offset|. Data in |blk| are moved down to make room; no data is lost.
// |insert| makes a larger block to accommodate the inserted data, and returns a pointer
// to this larger block, which the caller is expected to use instead of |blk|.
*/
It does not print the correct tmp variable I do not why
int *insert(int *blk, int *toInsert, int dim1, int dim2, int offset) {
int *tmp = calloc(dim1+dim2, sizeof(int));
int i = 0;
do{
tmp[i++] = *blk++;
printf("%d", tmp[i]);
}while(offset--);
return tmp;
}
Explanation / Answer
First of all in the given code you are updating the i then trying to print the location.
tmp[i++] = *blk++;
printf("%d", tmp[i]);
which should be like :
tmp[i] = *blk++;
printf("%d", tmp[i]);
i++;
still the logic is not correct as it is not inserting the elements of toInsert from the offset
Try this instead:
int *insert(int *blk, int *toInsert, int dim1, int dim2, int offset) {
int *tmp = calloc(dim1+dim2, sizeof(int));
int i = 0,j;
//First lets insert the elements till offset from blk to temp
for(j=0; j<offset; j++,i++)
{
tmp[i] = blk[j];
printf("%d", tmp[i]);
}
//Then insert the toInsert elements
for(int k=0; k<dim2; k++,i++)
{
tmp[i]=toInsert[k];
printf("%d", tmp[i]);
}
//Then insert the remaining elements from blk
for( ; j<dim1; j++, i++)
{
tmp[i]=blk[j];
printf("%d",tmp[i]);
}
return tmp;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.