C Programming - Pointers - Discussion

Discussion Forum : Pointers - Find Output of Program (Q.No. 21)
21.
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;
}
Alice
ecilA
Alice lice ice ce e
lice ice ce e
Answer: Option
Explanation:

If you compile and execute this program in windows platform with Turbo C, it will give "lice ice ce e".

It may give different output in other platforms (depends upon compiler and machine). The online C compiler given in this site will give the Option C as output (it runs on Linux platform).

Discussion:
59 comments Page 2 of 6.

Rohit Jindal said:   1 decade ago
n=strlen(x);gives n=5
*x=x[5]; can be written as *(x+0)=x[5] and x[5] contains
'/0' so 'A' will be replaced by '/0' since
x[0] contains 'A'
x[1] contains 'l'
x[2] contains 'i'
x[3] contains 'c'
x[4] contains 'e'
x[5] contains '/0'

Amit Wadhe said:   1 decade ago
n=strlen(x);
gives n=5
*x=x[5]; can be written as *(x+0)=x[5]
and
x[5] contains '/0' so 'A' will replcd by '/0' since

Now our string will be like this:
x[0]='\0'
x[1]='l'
x[2]='i'
x[3]='c'
x[4]='e'
x[5]='\0'

So in 1st iteration i print \0lice
2nd : ice
3rd : ce
4th : e
5th : \0
i.e lice ice ce e

Rajesh said:   1 decade ago
n=strlen(x);
gives n=5
*x=x[5]; can be written as *(x+0)=x[5]
and
x[5] contains '/0' so 'A' will replcd by '/0' since

Now our string will be like this:
x[0]='\0'
x[1]='l'
x[2]='i'
x[3]='c'
x[4]='e'
x[5]='\0'

Now look carefully :-

string become x[]={'\0','l','i','c','e','\0'};
for loop will be execute 6 times from i=0 to i=5

1st : at first position it find end char ('\0') so it will print nothing and x is incremented by 1 byte
2nd : x => l so it will print rest of string "lice" ,x++
3rd: x=>i so print "ice" and x++
4th: x=> c so print "ce" and x++
5th: x=> e so print "e" and x++
6th:x=> '\0' so nothing will be printed
at last printf("%s",x) will print nothing bz x =>'\0'
so result will be => lice ice ce e
(1)

Rupinderjit said:   1 decade ago
Rajesh's explanation is 100% relevant and correct.Thanks buddy.

SonaliA said:   1 decade ago
Not getting following statement.

x[5] contains '/0', so 'A' will replaced by '/0'

How?

Nandu said:   1 decade ago
@sonalia;'\0' means null value. So it does not print anything.

Gowthami said:   1 decade ago
if x[5] is '/0' then how 'A' will be replaced by '/o'.

Please give clear explanation.

Gouri said:   1 decade ago
I did't get how '\0' is at the first position ?

Ashwini said:   1 decade ago
but x[i]=*(x+i),then how is x[5]=*(x+0) ???

Sakshi said:   1 decade ago
I dont understand that how the pointer after reaching the end gets back to print "lice" and so on...


Post your comments here:

Your comments will be displayed after verification.