简体   繁体   English

问题要求使用指针返回字符串的一部分

[英]Questions asks to work with pointers to return portion of string

int main (void)
{
char c[] = "KATEWINCE";
char *p =c;
printf("%s", p+p[3]-p[1]) ;
return (0);
}

The output is WINCE but I don't get how the code is working, please explain.输出是 WINCE 但我不明白代码是如何工作的,请解释一下。

You assigned 0x45 to c[3] / p[3] .您将 0x45 分配给c[3] / p[3] [1] [1]

You assigned 0x41 to c[1] / p[1] .您将 0x41 分配给c[1] / p[1] [1] [1]

So p + p[3] - p[1] is equivalent to p + 0x45 - 0x41 .所以p + p[3] - p[1]等价于p + 0x45 - 0x41

This attempts to advance p by 0x45 elements.这试图将p推进 0x45 个元素。 This is undefined behaviour.这是未定义的行为。 You can advance a pointer to the position immediately following the object to which it points, but no further.您可以将指针前进到紧跟在它指向的对象之后的位置,但不能再向前移动。 c is simply not that large. c根本没有那么大。

But let's say c was far larger.但是让我们说c大得多。 You would see the same result as you posted here.您会看到与您在此处发布的结果相同的结果。

p is advanced by 0x45 elements, then reversed by 0x41 elements. p前进 0x45 个元素,然后反转 0x41 个元素。 The net result is that p is advanced by 4 elements.最终结果是p提前了 4 个元素。 And that's exactly what we see.而这正是我们所看到的。


  1. Assuming an ASCII-based machine.假设是基于 ASCII 的机器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM