Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program ?

#include <stdio.h>
#include <string.h>

int main()
{
    int i, n;
    char *x="Alice";
    n = strlen(x);
    *x = x[n];
    for(i=0; i<=n; i++)
    {
        printf("%s ", x);
        x++;
    }
    printf("\n", x);
    return 0;
}

 

  • A.Alice
  • B.ecilA
  • C.Alice lice ice ce e
  • D.lice ice ce e

Answer: D

Correct answer: lice ice ce e

x[n] is the terminating null, and *x = x[n] writes it over the first character, so the string becomes an empty string followed by lice.

The first iteration therefore prints nothing before its space. Each subsequent iteration advances x by one and prints the remaining tail - lice, ice, ce, e. Note that x points to a string literal, so writing through it is undefined behaviour and would fault on many modern systems.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.