CodeFreak
CodeFreak

Reputation: 110

How to complete function to use pointer arithmetic instead of array subscripting in C?

I am struggling with specific parts in my code that I seem to have formatted wrong. This code was taken from my programming book and the parts that were blank have a '$' around them. However, there are two blanks I can't seem to figure out. My current code is:

int sum_two_dimensional(const int a[][LEN], int n)
{
  int i,j, sum = 0;
  for(i=0, i<n; i++)
     for(j = 0; j< LEN; j++)
       sum+=a[i][j];
  return sum;
}

int sum_two_dimensional_array(const in a[][LEN], int n)
{
  int *p, sum = 0;

  for(p= a[0]; p < a[0] ______; p++)
      sum += ________;                     //my guess is a[p][sum];
  return sum;
}

I tried several things in these blanks an it seems that I keep getting errors. I do not fully understand the array/pointer situation. The blanks that I filled in, (encased in $$$), I feel are right but feel free to double check me. I appreciate any help.

Upvotes: 1

Views: 1130

Answers (1)

xvan
xvan

Reputation: 4855

This exploits the fact that an array a[N][M] uses the same memory as a single dimension array a[N*M]

So you can "safely" iterate a[0] "out of bound" without triggering memory exception up to the index a[0][N*M-1]

int sum_two_dimensional_array( int a[][LEN], int n)
{
  int *p, sum = 0;

  for(p= a[0]; p < a[0]+n*LEN; p++)
      sum += *p;
  return sum;
}

Upvotes: 1

Related Questions