在 C 语言中有没有一种方法可以做这样的事情:
/* it's a demo code. I know that it doesn't work. */
char foo[] = "abc";
char* p = &foo[0];
int len = 3;
while(len) {
printf("%c", *p);
p--;
len--;
}
并获得 cba
输出?
我的问题是:有什么简单的方法可以做到这一点?也许使用算术指针。我知道我可以写一个函数:
/* Note: I haven't tested the this code. But I believe that works. */
char *strrev(char input[]) {
if (input == NULL) return NULL;
int len = strlen(input) - 1;
char * rev = malloc(len+1);
if (rev == NULL) return NULL;
for (; len != 0; len--) *rev++ = input[len];
if (len == 0) {
*rev++= '\0';
return rev;
} else {
free(rev);
return NULL;
}
}
但我正在寻找更简单的方法,我需要编写一个从半个字符串开始比较的函数。
最佳答案
void backwards_print(const char *text) {
/* don't even try to print an empty string */
if (*text) {
const char *p = text;
/* go to the end */
while (*p++) /* void */;
/* print from the end */
while (p != text) putchar(*--p);
}
putchar('\n'); /* newline, flush buffer */
}
示例用法
char foo[] = "abc";
backwards_print(foo);
关于c - 是否可以访问 "recursive mode"中的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9945895/