Originally Posted by
sorayaj
why should I write "(int *)" for passing the matrix to the readMatrix function? Is it passing the pointer to the location of the matrix[4][4] in memorry?
When an array is passed as an argument, it is converted to a pointer to its first element. matrix is an int[4][4], so when passed as an argument an int(*)[4] is passed instead, but this is not compatible with the int* parameter, hence the cast to silence the likely compiler warning.
Originally Posted by
sorayaj
can I pass it using ampersand like &matrix?
Yes, and I feel that it would be better style:
Code:
readMatrix("matrix1.txt", &matrix[0][0]);
On the other hand, readMatrix assumes a 4 by 4 matrix, so I'd argue that even better yet would be to change readMatrix:
Code:
void readMatrix(char *filename, int (*matrix)[4])
{
FILE *fp = fopen(filename, "r");
if (fp)
{
int i, j, val;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
if (fscanf(fp, "%d", &val) == 1)
{
matrix[i][j] = val;
}
else
{
/* record a special error value? report a read error? */
}
}
}
fclose(fp);
}
else
{
/* report a file open error? */
}
}
Now you can write:
Code:
void p1(void)
{
int matrix[4][4];
readMatrix("matrix1.txt", matrix);
}
EDIT:
Incidentally, filename should be a const char* rather than just a char* because you clearly do not intend to modify the string.