指针算术和字符数组

时间:2017-09-13 22:05:33

标签: c pointers pointer-arithmetic

我无法理解以下代码。虽然我试图调试它一段时间似乎我无法理解代码的确切机制,我感到卡住了。任何帮助都将深表感谢。

编辑:我的问题主要在于递归函数以及如何知道何时停止自我调用。

    randomNum = Math.floor((Math.random() * quotes.length));
    randomQuote = quotes[randomNum];
    randomAuthor = author[randomNum];

    $("#quote").text(randomQuote);
    $("#author").text(randomAuthor);
}

$("#newQuote").on('click', function() {
    getQuote();
});

1 个答案:

答案 0 :(得分:0)

递归函数调用在doSomethingELSE(w+1)得到" bcdfb"," cdfb"," dfb"," fb" ," b","" - > if(w[0] == '\0') return。这会为每个char放置一个函数调用的执行堆栈,然后向后移动。 static变量s向前发展。清理后,更清楚会发生什么:

#include <stdio.h> /* printf */
#include <string.h> /* strlen */

/* prototype */
void swapConsectutiveLetters(char * word);

/** Provides a word. */
int main(void) {
    char word[10] = "abcdfb";
    swapConsectutiveLetters(word);
    printf("%s", word);
    return 0;
}

/** Detects consecutive letters occurring in the n-th from first,
 last and swaps them. */
void swapConsectutiveLetters(char * word) {
    char * end;
    /* Do nothing: null, empty, or 1-char string. */
    if(!word || word[0] == '\0' || word[1] == '\0') return;
    /* Obtain a pointer to the end of the string. */
    end = word + strlen(word) - 1;
    /* Swaps consecutive letters. */
    do {
        if(end[0] - word[0] == 1) {
            char temp = word[0];
            word[0]   = end[0];
            end[0]    = temp;
        }
    } while(++word < --end);
}