1

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.

13
  • It would be really useful to know which book it is. Commented Oct 27, 2016 at 3:36
  • @Troy C programming, a modern approach. Version 2 Commented Oct 27, 2016 at 3:40
  • what is in ? ... Commented Oct 27, 2016 at 3:42
  • The title says you want to rewrite a function, but the question suggests you want to know what to put in the blanks. Which is it? Commented Oct 27, 2016 at 3:43
  • 1
    @CodeFreak you first need to understand using a pointer to iterate over a 1-D array. I'd suggest reading material on that first. Once you understand that then this will be a small step on top of that. (*p is the same in both cases, it is just specifying the end condition that is slightly different for the 2-D array) Commented Oct 27, 2016 at 4:07

1 Answer 1

1

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;
}
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.