int a[NUM_ROWS][NUM_COLS], (*p)[NUM_COLS], i=5;
//pointer can point to an array of length 'Length Columns'
Let's iterate it
for(p=&a[0]; p<&a[NUM_ROWS]; p ){
(*p)[i]=0;
}
My (incomplete) understanding is that p is pointing to the location of array ' a's ' 0th index location, this is stored as a 1-D array of length [NUM_COLS]. How is this making the array column 'i' to reset itself to 0. How is pointer jumping to next column location?
I know that a 'p i' refers to 'address of a 4*i bytes' so how is 'address of a x bytes' happening in column wise iteration using pointer to an array,
CodePudding user response:
p
is a pointer to a whole row of the array, so p
makes it point to the next row. By setting the [i]
entry to 0 in every row, you set the entire i
-th column to 0.
I know that a 'p i' refers to 'address of a 4*i bytes' so how is 'address of a x bytes' happening in column wise iteration using pointer to an array,
This is not true.
CodePudding user response:
Instead of this expression in the for loop
p=&a[0];
you could just write
p = a;
Array designators used in expressions are implicitly converted (with rare exceptions) to pointers to their first elements.
So dereferencing the pointer *p
you will get the element of the two-dimensional array pointed to by the pointer p
. In case of the array a
elements of the array has the type int[NUM_COLS]
.
In turn the array designator *p
used in the expression (*p)[i]
also is converted to pointer to its first element of the type int *
. And the expression (*p)[i]
yields the i-th element of the one-dimensional array pointed to by the pointer p
.
The for loop can look like
for( p = a; p < a NUM_ROWS; p )
{
(*p)[i]=0;
}
That is the i-th element of each "row" of the two dimensional array is set to 0.
To make it more clear consider a one dimensional array.
int a[NUM_ELEMENTS};
then a pointer to the first element of the array looks like
int *p1 = a;
A pointer to the whole array as one object looks like
int ( *p2 )[NUM_ELEMENTS] = &a;
And you may write
p1 = *p2;
because the expression *p2
yields the array a
.
As for your statement
I know that a 'p i' refers to 'address of a 4*i bytes' so how is 'address of a x bytes' happening in column wise iteration using pointer to an array,
then actually the expression p i
refers to the i-th element of the two dimensional array the offset of the address of which is equal to the value i * sizeof( int[NUM_COLS] )
that is equivalent to i * NUM_COLS * sizeof( int )
.