带循环和变量的数组

时间:2011-11-15 00:33:49

标签: c arrays loops

我正在尝试了解更多,但我试图理解下面附带的代码,但我不能。请向我解释一下。提前致谢。

#include <stdio.h>

int main (void)

{

    int ratingCounters[11], i, response;

    for ( i=1; i<=10; ++i)
        ratingCounters [i] = 0; // how does this affact the array?

    printf("enter the response number ");


    for (i=1; i<=20; ++i)
    {

        scanf("%d", &response);

        if (response < 1 || response > 10 )

            printf("bad response %i ", response);
        else
            ++ratingCounters[response];// storing responses and the ++ ... how does it work?
    }

    printf("\n rating number of response \n");
    printf("----- ---------------------\n");

    for (i=1; i<=10l; ++i)
        printf("%4i%14i\n", i, ratingCounters[i]);

    return 0;

}

3 个答案:

答案 0 :(得分:1)

我在这段代码中发现了两个明显的问题。让我列出一下:

  • for (i=1; i<=20; ++i) - 草率变量重用,可以错误地解释为缓冲区溢出
  • for (i=1; i<=10l; ++i) - 是10L还是101 始终 大写后缀文字

请记住,有4种常量:01-1和标记常量。

另外,不要轻易地重复使用变量。当i是您的索引时,请将其视为此类。重新使用i来实现输入计数器是错误的。

OP,您需要阅读K&amp; R.

答案 1 :(得分:0)

你不明白哪一部分?这是非常基本的C,你的熟练程度是多少?绝对的菜鸟?在阅读更多代码之前,您可能应该停下来阅读一本关于C基础知识的书,但是在评论中可以快速了解您的问题。

for ( i=1; i<=10; ++i)
    ratingCounters [i] = 0; // how does this affact the array?

这个循环是(尝试)将数组中的每个元素初始化为0.当你声明一个这样的数组时:

int array[11];

11 int的空间在堆栈上保留,但它们不会初始化为任何特定值。循环(错误地)跳过元素0。循环应该是:

for ( i=0; i < 11; ++i)
    ratingCounters [i] = 0;

任何中途不错的优化编译器都会优化循环。

++ratingCounters[response];// storing responses and the ++ ... how does it work?

此行正在递增ratingCounters[response]处的值。对于每个响应,它计算已输入该类型的数量。

答案 2 :(得分:0)

正确的最后一个循环:

for (i=0; i<=10; i++)
    printf("%4i%14i\n", i, ratingCounters[i]);

数组的第一个元素是:ratingCounters [0]。 eleventhone是:ratingCounters [10]。

`++ratingCounters[response]` is the same thing as :

ratingCounters[response] = ratingCounters[response] + 1

当它为0时,该指令将其递增为1.原因由Ed S的答案描述。

这也是缓冲区溢出:

for ( i=0; i < 11; ++i)
    ratingCounters [i] = 0;

这个循环写入ratingCounters [11]或数组的最后一个元素,第11个是ratingCounters [10]