954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

String Pointer

The output of this code is "lice ice ce e". Seems to be string array is acting like a circular array. But how is it possible ????

#include<stdio.h>
#include<conio.h>

void main()
{
 int i,n;
 char *x="Alice";
 clrscr();
 n=strlen(x);
 *x=x[n];
 for(i=0;i<n;i++)
 {
  printf("%s ",x);
  x++;
 }
 getch();
}
ram619
Light Poster
46 posts since Mar 2010
Reputation Points: 6
Solved Threads: 0
 

%s prints the whole string. If the starting point for the string steps ahead by one character each iteration, you basically chop off the first character each time.

char const* x = "Alice";

printf("%s", x); // "Alice"
++x;
printf("%s", x); // "lice"
++x;
printf("%s", x); // "ice"
++x;
printf("%s", x); // "ice"
++x;
printf("%s", x); // "ce"
++x;
printf("%s", x); // "e"

By the way, this line:

*x=x[n];

is very bad. x is a pointer to a string literal, and string literals are not allowed to be modified. But that statement tries to overwrite the first character of the string literal with the last.

deceptikon
Indubitably
Administrator
632 posts since Jan 2012
Reputation Points: 119
Solved Threads: 105
 

deceptikon Thanks.......... got it now ......... Thread Solved...........

ram619
Light Poster
46 posts since Mar 2010
Reputation Points: 6
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You