Reputation: 73
Why can I access an array of pointers with two parameters, when it's defined as one-dimensional?
I know, I have to work with an array of pointers to access a multi-dimensional array in a function, but I don't know why I can access the array of pointers with two parameters.
int a[m][l] { 1,2,3,4, 2,3,4,5, 3,4,5,6 }; //some matrices
int c[m][l];
int *ap[m]; //array of pointers one-dimensional
int i,j;
for (i = 0; i < m; i++) //passing the address of first element in each
ap[i] = a[i]; //colon of matrix to array of pointers
for (j = 0; j < m; j++)
bp[i] = b[i];
dosomethingwithmatrix(ap[0], bp[0], m, l);
int* dosomethingwithmatrix(const int*ap[], int* bp[])
{
cp[i][j] = ap[i][j] //accss the array of pointers with two parameters
}
Upvotes: 2
Views: 3228
Reputation: 9416
Also in C an array is said to decay into a pointer.
From the standard (C99 6.3.2.1/3 - Other operands - Lvalues, arrays, and function designators):
Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.
So:
array[i] "decays" to pointer[i]
where pointer has the address of the [0]th element of array
And since we have already seen that:
p[i] == *(p + i)
all we are doing is adding offsets to pointers.
BTW, since addition is commutative, *(p + i) == *(i + p)
, it gives the sometimes surprising result that:
3["hello world"]
is a perfectly valid C expression (and it equals "hello world"[3]
).
Upvotes: 2
Reputation: 134286
In your case, ap[i][j]
is allowed because, it is meaning ful.
Let's check the data types.
For int *ap[m];
, ap
is an array of int *
s. In case of the function parameter int*ap[]
, ap
is a pointer to a pointer-to-int.
Then, ap[k]
(referring to the previous point) is an int *
. This may very well be allocated memory which can provide valid access to more that one int
s.
Provided enough memory allocated, ap[k][s]
will refer to an int
.
Upvotes: 1
Reputation: 105992
Both of the parameters ap
and bp
of function dosomethingwithmatrix
are pointer to pointer to int. They are not array of pointers. The function declarator
int* dosomethingwithmatrix(const int *ap[], int *bp[])
is equivalent to
int* dosomethingwithmatrix(const int **ap, int **bp)
Upvotes: 0
Reputation: 53006
Because you can dereference the pointer with index notation. First you access the element (the pointer) with an index, now the pointer can be dereferenced too with an index.
The equivalency between that and the indirection operator is as follows
pointer[i] == *(pointer + i);
Upvotes: 1