NO

Author Topic: Problem with array  (Read 2797 times)

verdu60

  • Guest
Problem with array
« on: October 08, 2015, 07:33:33 AM »
Hello.
By transfer to the function accepting the constant array, not constant data...
The one-dimensional array - the program is compiled...
The two-dimensional array - the program isn't compiled...(error #2140)
Why?
Code: [Select]
#include <stdio.h>
#define COLS 4
int sum (const int ar[], int n);
int sum2d(const int ar[][COLS], int rows);
int main(void)
{
int total1, total2;
int *pt1;
int (*pt2)[COLS];
pt1 = (int [COLS]) {15, 35,-10,60};
total1 = sum(pt1, COLS);
pt2 = (int [2][COLS]) { {1,2,3,-9}, {4,5,6,-8} };
total1 = sum(pt1, COLS);//not error
total2 = sum2d(pt2, 2); //error #2140: Type error in argument 1 to 'sum2d'; expected 'const int (*)[4]' but found 'int (*)[4]'.

printf("total1 = %d\n", total1);
printf("total2 = %d\n", total2);
return 0;
}

int sum(const int ar[], int n)
{
int total = 0;
for(int i = 0; i < n; i++)
total += ar[i];
return total;
}

int sum2d(const int ar[][COLS], int rows)
{
int r;
int c;
int tot = 0;
for(r = 0; r < rows; r++)
for(c = 0; c < COLS; c++)
tot += ar[r][c];
return tot;
}

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2115
Re: Problem with array
« Reply #1 on: October 08, 2015, 10:00:00 AM »
Other C99 compilers don't produce error
gcc,  msvc 2013

only gcc 3.45 gives warning
Code: [Select]
test_arrays1.c:11: warning: passing arg 1 of `sum2d' from incompatible pointer type
May the source be with you