开发者

C, pointer, string

开发者 https://www.devze.com 2023-03-04 18:38 出处:网络
main() { char *x=\"girl\"; int n,i; n=strlen(x); *x=x[n]; for(i=0;i<n;i++) { printf(\"%s \\n\",x); x++; } } What is the output?
main()
{
  char *x="girl";
  int n,i;
   n=strlen(x);
  *x=x[n];
  for(i=0;i<n;i++)
  {
   printf("%s \n",x);
    x++;
  }
}

What is the output?

Please explain the output.......................

o/p is开发者_Python百科 :

irl
rl
l


The output is undefined behaviour. You modified a string literal.


As others have pointed out, the program as written has undefined behaviour.

If you make a small alteration:

char x[] = "girl";

then I believe it is legal, and possible to explain. (EDIT: Actually there are still problems with it. It's int main(), and you should return 0; at the end. You also need to #include <string.h> because you are using strlen, and #include <stdio.h> because you are using printf.)

The line

*x = x[n];

sets x[0] (i.e. *x) to x[4] (which happens to be the string terminator '\0'). Thus the first string to be printed is the empty string, because the very first character is the string terminator.

We then loop through the string, one character at a time, printing the substrings:

irl
rl
l


While the result is undefined behavior, as DeadMG said, let's assume you declared x as char x[] = "girl".

You assign 4 to n (since the length of the word "girl" is 4), and you assign the value in x[4] to *x (which is x[0]), but this value is '\0' (null terminator)

Now you loop and print the word from x to the next null terminator, but the first time, the first char is the null terminator, so you get nothing. after that you print the word from incrementing index.

g   i    r   l   \0

*x = x[4]:

\0   i    r    l   \0
^    ^    ^    ^
it1  it2  it3  it4      // << Where does x points to in each iteration of the for loop


The code is distictly suspect. *x=x[n] attempts to overwrite the literal "girl", and the effect will vary between platforms and compilers. More correctly it should be declared as:

const char *x = "girl";

and then it will not (should not) compile.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号