Reputation: 13
I am confused on incrementing pointers for arrays and then measuring the difference in bytes for the pointer locations.
I understand that a pointer *p
will increment by the datatype's size when moving though a multi-dimensional array. However, when an array, thisArray
is used:
int thisArray[ 7 ][ 4 ];
How should thisArrray + 1
be evaluated? Do I increment both rows and columns?
I want to know by by how many bytes apart will these pointers will be in memory.
I know the exact answer will be platform dependent. I am seeking the method of solution, not the exact answer.
Since I can't format code in the comments: I am putting it here:
// Using sizeof
#include <stdio.h>
int main(void) {
int tbl[ 7 ][ 4 ];
// Size of tbl
int x = sizeof(*tbl);
printf ( "%d\n" , x);
// Size of tbl + 1;
int y = sizeof(*tbl+1);
printf( "%d\n", y);
//Size apart in bytes
int z = y - x;
printf("%d\n", z);
return 0;
}
Upvotes: 1
Views: 477
Reputation: 417
When you use an index by itself it will be multiplied by the size as defined by the type. Assuming your int is 4 bytes, then each int will be 4 bytes apart in an array of type int. This is how your second or inner index (4) would work.
Check-out this good answer: How are multi-dimensional arrays formatted in memory?
To understand the first index (7), note that a two dimensional array is actually an array of arrays. In our example the second dimension is four elements wide, so you'll skip 4x4=16 bytes for each increment of your 1st index. So thisArray is an address in memory and [2][3] would add 2x16+3x4=44 bytes. That's the 4+4+3=11th consecutive spot in memory, where each spot is 4 bytes.
Upvotes: 0
Reputation: 206697
how should thisArrray + 1 be evaluated?
When thisArray
decays to a pointer, the pointers type is int (*)[4]
. The type of thisArray+1
is the same.
Do I increment both rows and columns?
Yes.
If you look at the memory of thisArray
using a row and column structure, you have:
thisArray -> +----+----+----+----+
| | | | |
thisArray + 1 -> +----+----+----+----+
| | | | |
thisArray + 2 -> +----+----+----+----+
| | | | |
thisArray + 3 -> +----+----+----+----+
| | | | |
thisArray + 4 -> +----+----+----+----+
| | | | |
thisArray + 5 -> +----+----+----+----+
| | | | |
thisArray + 6 -> +----+----+----+----+
| | | | |
thisArray + 7 -> +----+----+----+----+
If you want to use traverse elements of the array, you can either use indices or pointers.
Traversing using indices:
for ( int i = 0; i < 7; ++i )
{
for ( int j = 0; j < 4; ++j )
{
// Use thisArray[i][j];
}
}
Traversing using pointers:
for ( int (*ptr1)[4] = thisArray; ptr1 < thisArray+7; ++ptr1 )
{
for ( int* ptr2 = *ptr1; ptr2 < *ptr1 + 4; ++ptr2 )
{
// Use *ptr2
}
}
From a readability point of view, using indices to traverse the array is much more intuitive. I strongly recommend using that.
Upvotes: 5