简体   繁体   English

字符指针和数组

[英]Character pointer and array

The code snippet is: 该代码段是:

char c[]="gate2011";
char *p=c;
printf("%s",p+p[3]-p[1]);

The output is: 2011 输出是:2011

Can anyone explain how it came? 谁能解释它的来历?

-----Thanks in advance----- - - -提前致谢 - - -

Going through each line in turn: 依次浏览每行:

 char c[] = "gate2011";

Let's assume that array c is located at memory address 200. 假设数组c位于内存地址200。

 char *p = c;

p is now a pointer to c. p现在是指向c的指针。 It therefore points to memory address 200. The actual content of p is "200", indicating the memory address. 因此,它指向存储器地址200。p的实际内容是“ 200”,表示存储器地址。

  printf("%s", p + p[3] - p[1]);

The value of p is 200 when we treat it like a pointer. 当我们将其视为指针时,p的值为200。 However, we can also treat it like an array. 但是,我们也可以将其视为数组。 p[3] gets the value of the 4th item in the string, which is "e". p [3]获取字符串中第四个项目的值,即“ e”。 C stores characters as their ASCII value. C将字符存储为其ASCII值。 The ASCII value of "e" is 101. ASCII值“ e”为101。

Next, we get the value of p[1]. 接下来,我们得到p [1]的值。 p[1] == "a", which has an ASCII value of 97. Substituting these into the function: p [1] ==“ a”,其ASCII值为97。将它们替换为函数:

  printf("%s", 200 + 101 - 97);

That evaluates to: 评估结果为:

  printf("%s", 204);

At memory address 204, we have the string "2011". 在内存地址204,我们有字符串“ 2011”。 Therefore, the program prints "2011". 因此,程序将打印“ 2011”。

I'm not sure why you'd want to do something like this, but anyway, this is what's happening. 我不确定为什么要这样做,但是无论如何,这就是正在发生的事情。

p + p[3] - p[1]

Here you are taking a value of one pointer, and adding the value of the char at position 3, and then subtracting the value of the char at position 1. The char values are being implicitly cast to numerical values before doing the addition and subtraction. 在这里,您获取一个指针的值,并在位置3处添加char的值,然后在位置1处减去char的值。在进行加法和减法之前,将char值隐式转换为数值。

If p is location 1000, then the sum 1000 + 101(ASCII for e) - 97(ASCII for a) will be made. 如果p为位置1000,则将得出总和1000 + 101(ASCII表示e)-97(ASCII表示a)。 Therefore the result is a pointer to location 1004 in memory. 因此,结果是指向存储器中位置1004的指针。 The %s in the printf then subsitutes the string that starts at this location, and ends with the special character '\\0'. 然后, printf中的%s替换以该位置开始并以特殊字符'\\ 0'结尾的字符串。 So the string is effectively clipped to "2011" (the first 4 letters are missed because 101 - 97 = 4). 因此,该字符串实际上被裁剪为“ 2011”(因为101-97 = 4,所以缺少前4个字母)。

If this still doesn't make sense, I'd suggest you have a good look at how arrays in C work. 如果这仍然没有道理,我建议您对C中的数组如何工作有个很好的了解。

What have you expected? 你期望什么? Why not? 为什么不?

p[3]-p[1] = 'e'-'a' = 4 p [3] -p [1] ='e'-'a'= 4
p+4 = "2011" p + 4 =“ 2011”

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

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