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 4 of 6.

Vikash kr kreshari said:   1 decade ago
But that you have given compiler that gives Alice lice ice ce e.

Ramdayal said:   1 decade ago
But in Linux gcc compiler it print segmentation fault.

Sumi naza said:   1 decade ago
In linux(GCC) it will give segmentation fault.

Because *x="alice" will store in code section n u can not change the data of code section because it "read only memory".

Hotcpu said:   1 decade ago
I understand the answer D. However, how C is produced on the linux?
Based on the GNU C manual, when an array is initialized by a string, the '\0' will automatically add to the array. So, why in the online compiler x[5] is A instead of '\0'?

Pratik said:   1 decade ago
I am getting option C in both inbuilt C compiler of indiaBix as well as on Turbo C.

Souptick said:   1 decade ago
I run this program in Linux based system and output will be segmentation fault.

Cause x is pointing to string constant "Alice". So when we try to modify the string constant through x it is a illegal access and throw a runtime error.

*x = x[n]; This line is causing the error.

Rajesh.T.K. said:   1 decade ago
Can a single variable hold both "Alice" string and base address of an array?

Ankur Sharma said:   1 decade ago
Compiler on this site gives this output:

Alice lice ice ce e

I don't know why ?

Vidyu said:   1 decade ago
char *x="Alice"; //means *x points to A

n=strlen(x); //n=5

*x=x[n]; //x[5]='\0' and *x points to A here we are assigning x[5] i.e \0 to to *x by this we are replacing A with \0.

Loop part is easy.

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.