c - 是否可以访问 "recursive mode"中的指针?

标签 c string pointers

在 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/

相关文章:

c - 读取变量时出错,无法访问地址 X 的内存

c - 为什么我会收到警告 "implicit declaration of function ' fopen_s'"以及如何摆脱它?

python - 在 Python 中从另一个列表中排除一个列表中的项目的有效方法

C 从指向 uint32_t 的指针转换为指向包含 uint32_t 的 union 的指针

c - 如何通过C中的结构传递矩阵的地址?

c++ - 现代 C++ 函数返回函数指针的方式

c - 向 Xcode 添加头文件

c - 用 C 语言进行 Win32 API 控制台编程

python - 使用 Pandas 快速去除标点符号

c - 初始化一个未知数量和未知长度的字符串数组