M
Mara Guida
Imagine I have an array of arrays of ints and want to sum all the
ints.
#include <stdio.h>
int sumints(int arr[3][3])
{
int c, r, s=0;
for (r=0; r<3; r++)
{
for (c=0; c<3; c++) {
s += arr[r][c];
}
}
return s;
}
int main(void)
{
int my_array[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
printf("sum of ints is %d\n", sumints(my_array));
return 0;
}
I tried to define the sumints() function with constant ints, but the
types are not compatible
int sumints(const int arr[3][3])
I understand arrays 'decay' into a pointer to their first element when
passed to functions.
I understand the elements of the array `my_array` are not int: they
are arrays[3] of int.
I tried several variations on the theme (mostly using typedefs) and
reached the conclusion that
a pointer to an array[3] of int is compatible with
1) a constant pointer to an array[3] of int
2) a pointer to a constant array[3] of int
3) a constant pointer to a constant array[3] of int
Why aren't
int (*a)[3] /* a is a pointer to an array[3] of int */
and
const int (*a)[3] /* a is a pointer to an array[3] of
constant int */
compatible types?
It shouldn't be too hard for the compiler to figure it out, right?
ints.
#include <stdio.h>
int sumints(int arr[3][3])
{
int c, r, s=0;
for (r=0; r<3; r++)
{
for (c=0; c<3; c++) {
s += arr[r][c];
}
}
return s;
}
int main(void)
{
int my_array[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
printf("sum of ints is %d\n", sumints(my_array));
return 0;
}
I tried to define the sumints() function with constant ints, but the
types are not compatible
int sumints(const int arr[3][3])
I understand arrays 'decay' into a pointer to their first element when
passed to functions.
I understand the elements of the array `my_array` are not int: they
are arrays[3] of int.
I tried several variations on the theme (mostly using typedefs) and
reached the conclusion that
a pointer to an array[3] of int is compatible with
1) a constant pointer to an array[3] of int
2) a pointer to a constant array[3] of int
3) a constant pointer to a constant array[3] of int
Why aren't
int (*a)[3] /* a is a pointer to an array[3] of int */
and
const int (*a)[3] /* a is a pointer to an array[3] of
constant int */
compatible types?
It shouldn't be too hard for the compiler to figure it out, right?