P1:
int * g (void) {
int x = 10;
return (&x);
}
P2:
int * g (void) {
int * px;
*px = 10;
return px;
}
P3:
int * g (void) {
int *px;
px = (int *) malloc (sizeof(int));
*px = 10;
return px;
}
Answer: (c)
x
is a local variable, and returning its address causes undefined behavior as x
ceases to exist once the function returns.px
is an uninitialized pointer, and assigning a value to *px
results in undefined behavior.malloc()
, ensuring the pointer remains valid after the function returns.j
at the end of the execution of the following C program?int incr(int i) {
static int count = 0;
count = count + i;
return (count);
}
int main() {
int i, j;
for (i = 0; i <= 4; i++)
j = incr(i);
}
Answer: (a)
count
is a static variable, meaning its value persists across function calls.incr(0) → count = 0
incr(1) → count = 1
incr(2) → count = 3
incr(3) → count = 6
incr(4) → count = 10
Consider the following declaration:
struct {
short s[5];
union {
float y;
long z;
} u;
} t;
Assume:
short
= 2 bytesfloat
= 4 byteslong
= 8 bytest
, ignoring alignment?Answer: (c)
short s[5]
requires 10 bytes (5 × 2 bytes).u
takes 8 bytes (maximum of float
and long
).printf("i = %d, &i = %x", i, &i);
Answer: (c)
Explanation: Tokens in C include keywords, identifiers, constants, operators, string literals, and separators. The above statement consists of 10 tokens:
printf
(
"i = %d, &i = %x"
(string literal),
i
,
&
i
)
;
struct node {
int i;
float j;
};
struct node *s[10];
node
.node
.Answer: (a)
s[10]
is an array of 10 elements.struct node
.s
stores addresses of node
structures rather than the structures themselves.These C programming questions cover essential topics like pointers, memory allocation, static variables, structures, and tokens. Understanding these concepts is crucial for technical interviews and competitive exams.