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

Discussion

What will be the output of the program ?

#include <stdio.h>

int main()
{
    char *names[] = { "Suresh", "Siva", "Sona", "Baiju", "Ritu"};
    int i;
    char *t;
    t = names[3];
    names[3] = names[4];
    names[4] = t;
    for(i=0; i<=4; i++)
        printf("%s,", names[i]);
    return 0;
}

 

  • A.Suresh, Siva, Sona, Baiju, Ritu
  • B.Suresh, Siva, Sona, Ritu, Baiju
  • C.Suresh, Siva, Baiju, Sona, Ritu
  • D.Suresh, Siva, Ritu, Sona, Baiju

Answer: B

Correct answer: Suresh, Siva, Sona, Ritu, Baiju

The array holds pointers, and the code exchanges two of them through the temporary t - the strings themselves are never touched or copied. So elements 3 and 4 swap places, giving Suresh, Siva, Sona, Ritu, Baiju. Swapping pointers rather than character arrays is exactly why an array of pointers is preferred for sorting strings.

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

Post your comment

Please log in or register to post a comment.