简体   繁体   中英

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

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.

 char *p = c;

p is now a pointer to c. It therefore points to memory address 200. The actual content of p is "200", indicating the memory address.

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

The value of p is 200 when we treat it like a pointer. However, we can also treat it like an array. p[3] gets the value of the 4th item in the string, which is "e". C stores characters as their ASCII value. The ASCII value of "e" is 101.

Next, we get the value of p[1]. p[1] == "a", which has an ASCII value of 97. Substituting these into the function:

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

That evaluates to:

  printf("%s", 204);

At memory address 204, we have the string "2011". Therefore, the program prints "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.

If p is location 1000, then the sum 1000 + 101(ASCII for e) - 97(ASCII for a) will be made. Therefore the result is a pointer to location 1004 in memory. The %s in the printf then subsitutes the string that starts at this location, and ends with the special character '\\0'. So the string is effectively clipped to "2011" (the first 4 letters are missed because 101 - 97 = 4).

If this still doesn't make sense, I'd suggest you have a good look at how arrays in C work.

What have you expected? Why not?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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