递归增量器

Ste*_*eve 2 c recursion

我正在编写一个递归函数,它接受一个char数组,它表示一个数字,以及一个指向该数组中数字的指针.该函数的要点是像++运算符一样递增数字.但是,当我尝试使用数字'819'时.它不会将其增加到'820',而是将其更改为'810'(它会增加最后一个数字,但不会执行我想要的递归).有人可以帮我解决这个问题吗?谢谢.

#include <stdio.h>

char* inc(char *num, char* p)
{   
    if( *p>='0' && *p<='8' )
    {
        *p++;
    }
    else if ( *p=='9' )
    {
        *p = '0';
        inc(num, --p);
    }

    return num;
}

main()
{
    char x[] = "819";

    printf("%s\n", inc(x, x+strlen(x)-1) ); //pass the number and a pointer to the last digit
}
Run Code Online (Sandbox Code Playgroud)

aJ.*_*aJ. 11

改变*p++ to (*p)++; 你想增加p中包含的数字.

   char* inc(char *num, char* p)
    {   
        if( *p>='0' && *p<='8' )
        {
            (*p)++;       //==> change
        }
        else if ( *p=='9' )
        {
            *p = '0';
            inc(num, --p);
        }

        return num;
    }
Run Code Online (Sandbox Code Playgroud)

编辑:

++运算符具有更高的优先级*.因此,

*p++ ==> *p then p++; // p's value before the increment.
Run Code Online (Sandbox Code Playgroud)

请参阅此处的优先顺序表.