-4

I've got a C program that I'd like to have pointers do the calculations instead of the subscripts. Here's the code:

/* rain */
#define TWLV 12
#define YRS 5 
main()

{
     static float rain [YRS][TWLV] = {
{10.2, 8.1, 6.8, 4.2, 2.1, 1.8, 0.2, 0.3, 1.1, 2.3, 6.1, 7.4},
{9.2, 9.8, 4.4, 3.3, 2.2, 0.8, 0.4, 0.0, 0.6, 1.7, 4.3, 5.2},
{6.6, 5.5, 3.8, 2.8, 1.6, 0.2, 0.0, 0.0, 0.0, 1.3, 2.6, 4.2},
{4.3, 4.3, 4.3, 3.0, 2.0, 1.0, 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.2}
        };
/* initialize rainfall data for 1970-74 */
int year, month;
float subtot, total;

printf( " YEAR  RAINFALL (inches)\n");
for ( year = 0, total = 0; year < YRS; year++ )
{ /* for each year, sum rainfall for each month */
    for ( month = 0, subtot = 0; month < TWLV; month++)
        subtot += rain[year][month];
    printf("%5d, %15.1f\n", 1970 + year, subtot);
    total += subtot; /*total for all years */
}
printf("\nThe yearly average is %.1f inches. \n\n", total/YRS);
printf("MONTHLY AVERAGES:\n\n");
printf("Jan Feb Mar Apr May Jun Jul Aug Sep Oct");
printf("Nov Dec\n ");

for ( month = 0; month < TWLV; month++)
{ /* for each month, sum rainfall over years */
for ( year = 0, subtot =0; year < YRS; year++)
    subtot += rain[year][month];
printf("%4.1f ", subtot/YRS);
}
printf("\n");
}

I'm struggling with arrays / pointers being used interchangably so if someone could provide an explanation that would be great.

Thanks!

8
  • 1
    Please indent your code correctly. Commented Oct 2, 2015 at 1:44
  • 4
    What is wrong with using subscripts? Commented Oct 2, 2015 at 1:48
  • 1
    And your definition of main() is wrong, are you using a very old book? Commented Oct 2, 2015 at 1:51
  • 1
    main() should be int main() and should have a return value. Commented Oct 2, 2015 at 2:04
  • 1
    main is an int - and it returns an int. Always. Pls: why are you not happy, specifically, with subscripts? Commented Oct 2, 2015 at 2:04

1 Answer 1

0

If the type of your array is float rain[YRS][TWLV], you can replace every instance of rain[i][j] with *(&rain[0][0] + (i*TWLV) + j). This won’t actually gain you anything, because the compiler does it anyway. However, you can also declare for ( float* p = &rain[0][0]; p < &rain[0][0] + YRS*TWLV; ++p ) and that might be faster because it eliminates pointer arithmetic inside the loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.