Multiple issues:
First, the type of m
in main
does not match the type of arr
in checkDiag
; int **
is not compatible with int [][100]
(which is shorthand for int (*)[100]
).
If you want the types to match up, declare m
as follows:
int (*m)[100]; // m is a *pointer* to a 100-element array of int
Then, when you allocate m
, do the following:
m = malloc( r * sizeof *m ); // allocates space for an r x 100 array of int
The advantage of this method is that you allocate the entire array in one operation, and the rows are guaranteed to be contiguous.
Note that if r
isn't 100, you won't be allocating a "square" matrix. This shouldn't be that much of an issue for what you're doing, though, because you're only reading and checking r
by r
elements. If you want to be a stickler, though, you could do this:
int r;
// get value of r
int (*m)[r] = malloc( r * sizeof *m );
This dynamically allocates an r
x r
array of int
. We're using variable-length array syntax (that is, using the variable r
to define the array size). Note that variable-length arrays were introduced with C99 and made optional in C2011; you'll want to make sure your implementation supports them1.
In this second case, you'll want to change the prototype of checkDiag
from
int checkDiag( int arr[][100], int size )
to
int checkDiag( int size, int arr[][size] )
size
must be declared before it can be used in a VLA declaration.
In either case, you'd simply call free( m );
to deallocate the array when you're done.
The second major issue is this line in checkDiag
:
if(arr[i][j]==arr[++i][++i])
This line invokes undefined behavior; you're updating the value of i
multiple times between sequence points, and you're trying to both use the old and incremented values in the same expression (even then, it doesn't make sense logically). Try something more like the following:
for ( i = 0; i < size - 1; i++ )
{
if ( arr[i][i] == arr[i+1][i+1] )
count++;
}
The final issue is the line
if(count=size)
You want to use ==
instead of =
here; you're just assigning size
to count
, and since the result is non-zero, setting h
to 1. Change that to
if ( count == size )
h = 1;
Alternately, you could ditch the h
variable altogether and just write
return count == size;
1. To do this programmatically, look for the feature macro __STDC_NO_VLA__
, like so:
#if defined( __STDC_NO_VLA__ )
#error "VLAs are not available for this implementation!"
#endif