OA. free
Free
IBM Quantitative Aptitude Core Computer Science Medium

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
Choose one option.
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:

  1. Line 1-3: Standard includes—OK.
  2. Line 5: int i;—OK, declares int variable.
  3. Line 6: char a[] = "String";—OK, a is an array initialized with a string.
  4. Line 7: char *p = "New String";—OK, p is a pointer to a string literal.
  5. Line 8: Temp = a;—OK, Temp receives the address of array a (arrays decay to pointers).
  6. Line 9: a = malloc(strlen(p) + 1);COMPILATION ERROR. Since a is an array, its name is a non-modifiable lvalue. Arrays cannot be reassigned; you cannot change what address a refers to. The compiler will reject this assignment before any runtime behavior occurs.