What will the following C program do?
IBM aptitude question, verified with a worked answer. Free to practise - no sign-up.
What will the following C program do?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main() {
int i;
char a[] = "String";
char *p = "New String";
char *Temp;
Temp = a;
a = malloc(strlen(p) + 1); // Line number: 8
strcpy(a, p); // Line number: 9
p = malloc(strlen(Temp) + 1);
strcpy(p, Temp);
printf("(%s, %s)", a, p);
free(p);
free(a);
} // Line number: 15
Show answer & explanation
Answer: B. Generate compilation error at line 8
In C, array names are non-modifiable lvalues. You cannot assign a pointer to an array name using a = malloc(...) because a is a constant address. The compiler will reject this with an error like "invalid lvalue in assignment". Array declarations decay to pointers in many contexts, but they cannot be reassigned.
Step-by-step Derivation:
Line-by-line analysis:
- Line 1-3: Standard includes—OK.
- Line 5:
int i;—OK, declares int variable. - Line 6:
char a[] = "String";—OK,ais an array initialized with a string. - Line 7:
char *p = "New String";—OK,pis a pointer to a string literal. - Line 8:
Temp = a;—OK,Tempreceives the address of arraya(arrays decay to pointers). - Line 9:
a = malloc(strlen(p) + 1);—COMPILATION ERROR. Sinceais an array, its name is a non-modifiable lvalue. Arrays cannot be reassigned; you cannot change what addressarefers to. The compiler will reject this assignment before any runtime behavior occurs.