【问题标题】:C compiler omits code, gives no errorsC 编译器省略代码,不给出错误
【发布时间】:2015-09-25 14:42:52
【问题描述】:

我正在做“Learn C the Hard Way”中的指针练习,其中一个额外的功劳是以相反的顺序打印循环,无论如何,我一直在试图让练习正确,我想出了这个代码:

#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 循环并打印最后一个循环。这段代码有什么问题?谢谢你。

【问题讨论】:

  • 您预计会看到什么错误?
  • 这是怎么回事(ages - cur_age) &gt;= count;?你知道吗?
  • 任何类型的错误都没有关系,我认为奇怪的是它没有任何输出。
  • for(cur_name = names, cur_age = ages; 这从开头而不是结尾开始。这就是它立即终止的原因——它已经到家了。
  • 哦,我真是个笨蛋,谢谢!

标签: c pointers gcc


【解决方案1】:

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

【讨论】:

  • 目的是从末尾开始并反向打印。找不到正确的起点时失败。
【解决方案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--){

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-16
    • 2011-05-23
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    相关资源
    最近更新 更多