# C指针算术[英] C pointer arithmetics

### 问题描述

```#include <stdio.h>

void strrev(char *p)
{
char *q = p;
while(q && *q) ++q;
for(--q; p < q; ++p, --q)
*p = *p ^ *q,
*q = *p ^ *q,
*p = *p ^ *q;
}

int main(int argc, char **argv)
{
do {
printf("%s ",  argv[argc-1]); strrev(argv[argc-1]);
printf("%s\n", argv[argc-1]);
} while(--argc);

return 0;
}
```

## 推荐答案

```void strrev(char *p) // Assumption: p is null
{
char *q = p; // now q is null
while(q && *q) ++q; // The loop is skipped, so q and p are both still null.
for(--q;
```

```    p < q;
```

```    ++p, --q)
*p = *p ^ *q,
```

```    *q = *p ^ *q,
*p = *p ^ *q;
}
```

```void strrev(char *p) // Assumption: *p is 0
{
char *q = p; // *q is 0
while(q && *q) ++q; // The second condition is not met so the body is skipped.
for(--q; // q now points *before valid memory*.
p < q  // And we compare an invalid pointer to a valid one.
```

## 其他推荐答案

```while(q && *q)
```

```while(q != NULL && *q != '\0')
```

## 其他推荐答案

while(q && *q)用于确保q不是NULL和*q不是NUL.如果q不指向NULL，则使用while(*q)也是合法的.

```void string_rev(char *p)
{
char *q = p;

if(q == NULL)
return;

while(*q) ++q;
for(--q; p < q; ++p, --q)
*p = *p ^ *q,
*q = *p ^ *q,
*p = *p ^ *q;

}
```

while(q && *q)，q如果p指向NULL，则可以是NULL指针，然后在输入环形主体之前终止循环.否则，整个操作都不能是NULL指针.现在，循环终止取决于*q.一旦q到达字符串的末端，*q变成0并终止.