C编译器省略了代码,没有错误

时间:2015-09-25 14:42:52

标签: c pointers gcc

我正在做的指导练习来自"学习C艰难的方式"而其中一个额外的功劳是以相反的顺序打印循环,无论如何,我正试图让练习正确,我想出了这个代码:

#include <stdio.h>

int main(int argc, char *argv[])
{
    // create two arrays we care about
    int ages[] = {23, 43, 12, 89, 2};
    char *names[] = {
        "Alan", "Frank",
        "Mary", "John", "Lisa"
    };
    // safely get the size of ages
    int count = sizeof(ages) / sizeof(int);

    // set up the pointers to the start of the arrays
    int *cur_age = ages;
    char **cur_name = names;

    // fourth way with pointers in a stupid complex way
    for(cur_name = names, cur_age = ages; (ages - cur_age) >= count;
        cur_name--, cur_age--){
        printf("%s lived %d years so far.\n", *cur_name, *cur_age);
    }
    printf("---\n");

    int i;
    for(i = 0; i < 5; i++){
        printf("%d\n", i);
    }

    return 0;
}

此代码既没有警告也没有错误!跳过奇怪的for循环并打印最后一个循环。这段代码有什么问题?谢谢。

2 个答案:

答案 0 :(得分:5)

(ages - cur_age)在循环开始时等于零,因此永远不会满足循环条件(ages - cur_age) >= count。此外,使用递减运算符将导致未定义的行为,因为您已经从每个数组的第一个元素开始。

答案 1 :(得分:2)

您需要使用:

// Let cur_age point to the last element of the array.
// Same with cur_name.
int *cur_age = ages + count - 1;
char **cur_name = names + count - 1;

for(; (ages - cur_age) >= 0; cur_name--, cur_age--){
相关问题