Question

Miscellaneous C knowledge. (Put all answers in the same q5.txt file, they’re all short.) (a) [2...

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?

Homework Answers

Answer #1

Solution (a):

For struct: size=sum of size of all variables

size = 5 double + 5 int = 5*8 + 5*2 = 40+10=50

For union: size=max of size of all variables

size=max(5doubles, 5ints) = 40

Solution (b):

Since no * character used with q it is a double type variable.

Using typedef, t is equla to double * so type of y is double* or double pointer.

Solution (c):

If there is no character to read, then getchar returns EOF, which is −1.

Solution (d):

feof(stdin) checks whether EOF has been read or not. So even on an emty file, first there needs to be a read of EOF and then only feof(stdin) returns true

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions