Week-12 Assignment Solution
Week-12 Assignment Solution
Solution: (c) The scope of the member name is confined to the particular structure, within
which it is defined
3. What is actually passed if you pass a structure variable to a function?
a) Copy of structure variable
b) Reference of structure variable
c) Starting address of structure variable
d) Ending address of structure variable
Answer: (a)
If you pass a structure variable by value without & operator, only a copy of the variable is
passed. So changes made within that function do not reflect in the original variable.
4. The program will allocate …….bytes to ptr. Assume sizeof(int)=4.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr;
ptr = (int*)malloc(sizeof(int)*4);
ptr = realloc(ptr,sizeof(int)*2);
return 0;
}
Solution: 8
First, using malloc 16 bytes were allocated. Thereafter, applying calloc the size is adjusted and
made 8.
Problem Solving through Programming in C
Week 12 Assignment Solution
a) abcd
b) bcd
c) cd
d) abcdfgh
Solution: (b)
First, the pointer points to the base of A. Then it's incremented by one to point to the element
b. While p is not pointing e, the loop keeps prints the elements one after another. Therefore,
the final answer is bcd.
7. What is the output of the following C code? Assume that the address of x is 2000 (in
decimal) and an integer requires four bytes of memory.
int main()
{
unsigned int x[4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
printf("%u,%u, %u", x+3, *(x+3),*(x+2)+3);
}
Solution: (a)
All these points to the same element. Therefore, the same value will be printed. This is an
example of pointer arithmetic in an 2D array.
Solution: (b) The fp is a structure which contains a char pointer which points to the first
character of a file.
int main()
{
struct hello{};
return 0;
}
Solution: (b)Member variables can be added to a structure even after its first definition
Problem Solving through Programming in C
Week 12 Assignment Solution
int main()
{
struct p p1[] = {1, 90, 62, 33, 3, 34};
struct p *ptr1 = p1;
int x = (sizeof(p1) / 3);
if (x == sizeof(int) + sizeof(char))
printf("True");
else
printf("False");
return 0;
}
a) True
b) False
c) No output
d) Compilation error
Solution: (b) Size of the structure is the maximum size of the variable inside structure. Thus,
the size of each element of structure p is 4 bytes (in gcc compiler, it can vary based on
compiler). Thus, sizeof(p1) is 6*4=24. x will be 24/3=8. In the next step,
sizeof(int)+sizeof(char) is 5 which is not equal to x. Hence, false will be printed.