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;
}
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 3 of 6.
Bunny said:
9 years ago
@Isaiah it is not due to null access.
In some compiler, it shows an error because x is a variable pointer to a constant string, so we can't change any character of the string because it's constant.
i.e *x=x[n]; its wrong.
If remove this line it will work fine.
In some compiler, it shows an error because x is a variable pointer to a constant string, so we can't change any character of the string because it's constant.
i.e *x=x[n]; its wrong.
If remove this line it will work fine.
Isaiah said:
10 years ago
1'st iteration printf get crashed due to null access. So need to add answer option with "system get crashed".
Vignesh M said:
10 years ago
Why Linux compiler give segment fault?
Abhishek said:
10 years ago
Hello guys, all the explanation is wrong regarding GCC.
Because here string is constant so we can't change the string content so here segmentation is dump because *x = x[5] of this.
We are trying to change a constant string which we can't do so output is segmentation fault.
Because here string is constant so we can't change the string content so here segmentation is dump because *x = x[5] of this.
We are trying to change a constant string which we can't do so output is segmentation fault.
Priya said:
10 years ago
Am getting option C while compiling. Please help me with right answer.
Devi said:
10 years ago
In gcc it gives segmentation fault because of 4th line.
Rahul said:
1 decade ago
*x=A, n=5, so *x=x[5] will replace A with '\0' so new string will be. '\0lice so first iteration will not print anything because of \0 first. Next iteration lice will print.ice.ce.e will be printed.
Jakir said:
1 decade ago
Its giving segmentation fault.
Ankitjain said:
1 decade ago
Just check in ubuntu if you put comment on line *x = x[n] then only you can got output.
Deepak S said:
1 decade ago
What is the last printf("\n", x) doing here?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers