Navigation

Thursday 11 October 2018

Why does "a const" make a C function unable to work ?

#include <stdio.h>
int sum(int n, int (*a)[n]);
int main(void)
{
    int junk[3][4] = {{2, 4, 5, 8}, {3, 5, 6, 9}, {12, 10, 8, 6}};
    int total = 0;
    for (int i = 0; i < 3; i++)
        total += sum(4, junk + i); 
    printf("%d\n", total);

    return 0;
}
int sum(int n, int (*a)[n])
{
    int subTotal = 0;
    for (int i = 0; i < n; i++)
        subTotal += (*a)[i];
    return subTotal;
}
Look at the above code which I want to calculate the sum of all elements from an array 3 of array 4 of integers.
It works nice.
Now I add a const to the function sum
#include <stdio.h>
int sum(int n, int const (*a)[n]);
int main(void)
{
    int junk[3][4] = {{2, 4, 5, 8}, {3, 5, 6, 9}, {12, 10, 8, 6}};
    int total = 0;
    for (int i = 0; i < 3; i++)
        total += sum(4, junk + i); 
    printf("%d\n", total);

    return 0;
}
int sum(int n, const int (*a)[n])
{
    int subTotal = 0;
    for (int i = 0; i < n; i++)
        subTotal += (*a)[i];
    return subTotal;
}
It can't be compiled. Here is the error message:
test.c: In function ‘main’:
test.c:8:3: warning: passing argument 2 of ‘sum’ from incompatible pointer type [enabled by default]
   total += sum(4, junk + i);
   ^
test.c:2:5: note: expected ‘const int (*)[(sizetype)(n)]’ but argument is of type ‘int (*)[4]’
 int sum(int n, const int (*a)[n]);
I thought non const should be able to be assigned to const
Where did I understand wrong?

Here might be the answer.

No comments:

Post a Comment