1

While executing the below code:

int main()
{
  int abc[3][3]={0};
  for(int *ip=&abc[0][0];ip<=&abc[3][3];ip++)
  {
    printf("%d   \n",*ip);
  }
}

Expected result is 9 zeros but it displays 12 data. What might be reason?

1 Answer 1

2

If you look at the memory layout of a 3x3 array, it looks like:

[0][0]          [1][0]        [2][0]         
+----+----+----+----+----+----+----+----+----+
|    |    |    |    |    |    |    |    |    |
+----+----+----+----+----+----+----+----+----+

Where is the element [3][3]?

[0][0]          [1][0]        [2][0]         [3][0]         [3][3] 
+----+----+----+----+----+----+----+----+----+----+----+----+----+
|    |    |    |    |    |    |    |    |    |    |    |    |    |
+----+----+----+----+----+----+----+----+----+----+----+----+----+

That explains why you end up accessing 12 elements.

Your code is subject to undefined behavior for accessing the beyond valid indices but that's another issue.

You could use:

for (int *ip = &abc[0][0]; ip <= &abc[2][2]; ip++)
{
  printf("%d   \n",*ip);
}

However, it is better to access a 2D array as a 2D array.

for (size_t i = 0; i < 3; ++i )
{
  for (size_t j = 0; j < 3; ++j )
  {
    printf("%d   \n", abc[i][j]);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes Its right. While printing last 3 values shows junk values instead zero.
@alk, <= is right. abc[2][2] is a valid element.

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.