In: Computer Science
Edit question
Miscellaneous C knowledge. (Put all answers in the same q5.txt file, they’re all short.)
(a) [2 marks] On an old 16-bit computer system and its C compiler,sizeof(double)=8andsizeof(int)=2. Given the two type definitions below, what weresizeof(s)andsizeof(lingling)on that system? Assume that ins, there is no gap between the twofields.
typedef struct s {
double r[5];int a[5];
} s;
typedef union lingling {
double r[5];int a[5];
} lingling;
(b) [2 marks] Given the following declarations, two questions: What is the type ofq? Whatis the type ofy?double* p, q;typedef
double *t;t x, y;
(c) [1 mark] To read a character from stdin, what’s wrong with “c = getchar();”, ifchasbeen declared with “char c;”?
(d) [3 marks] A beginner in C has coded up an attempt to determine whether stdin isempty:
#include <stdio.h>
int main(void){
if (feof(stdin)) {
printf ("empty\n");
else {
printf ("not empty\n");
}
return 0;
}
This is run with stdin redirected from an empty file. It mistakenly reports “not empty”.Help the beginner by briefly answering: Why is this approach ineffective? And what isa correct approach?
Question
a)
Given:
sizeof(double)=8 and sizeof(int)=2
typedef struct s {
double r[5];int a[5];
} s;
typedef union lingling {
double r[5];int a[5];
} lingling;
To find size of s and size of lingling
For s:
There are 5 double values=>5*8=40
There are 5 int values=>10
sizeof(s)=40+10=50
sizeof(s)=40
For lingling:
union is also like structure but it returns the max size among
the variables used
There are 5 double values=>5*8=40
There are 5 int values=>10
sizeof(lingling)=max(40,10)=40
sizeof(lingling)=40
Question
b)
Given
double* p, q;
typedef double *t;t x, y;
To find the type of q and type of y.
q is of type double.
y is of type t which is an alias for a pointer for type double
So y is pointer of double type.
Question c)
To read a character from stdin, what’s wrong with “c = getchar();”, if c has been declared with “char c;”?
For reading character from stdin there has to be an input.if not get char will return EOF.
Question d)
The EOF returns a boolean value in C.
If the value is 0 then there is no data.
Otherwise The data will be read.
SO the obvious code is
#include <stdio.h>
int main(void){
if (feof(stdin)==0)
{
printf ("empty\n");
}
else
{
printf ("not empty\n");
}
return 0;
}
This will print correctly as empty or not empty