Mrdour
Mrdour
2017-11-07 15:45

指针值与数组值不匹配

  • c
  • 指针

这是C Primer Plus中的一道题,代码如下:

#include <stdio.h>
#define MONTHS 12
#define YEARS 2
int main(void)
{
    const float rain[YEARS][MONTHS] = 
    {
        { 4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6 },
        { 8.5,8.2,1.2,1.6,2.4,0.0,5.2,0.9,0.3,0.9,1.4,7.3 }
    };
    int year, month;
    float total1 = 0, total2 = 0;
    const float (*rainp) [2] = rain;
    printf("两年降雨总量为:\n");
    for (year = 0; year < YEARS; year++)//以数组输出
        for (month = 0; month < MONTHS; month++)
        {
            printf("%4.1f", rain[year][month]);
            total1 += rain[year][month];
        }
    printf("\n\n%.2f\n", total1);
    for (year = 0; year < YEARS; year++)//以指针输出
        for (month = 0; month < MONTHS; month++)
        {
            printf("%4.1f", *(*(rainp + year) + month));
            total2 += *(*(rainp + year) + month);
        }
    printf("\n\n%.2f\n", total2);
    system("pause");
    return 0;
}

编译运行结果如下:

图片说明

其中红框部分是分别用数组和指针输出的数字,其范围为数组rain[0][0]到rain[0][11]第一行正确但是第二行出现偏差。而数组其他部分数值正常。我想请教一下这是为什么。

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答