【发布时间】:2015-01-14 16:28:57
【问题描述】:
我是 C 新手,我正在尝试编写一个函数来计算由 1 和 0 组成的矩阵中每一列的 1 的数量。这是我的代码:
#include <stdio.h>
void *countCols(int *output, int rows, int cols, int **matrix[5][5])
{
/*(int *output) is the pointer which we want the output stored at.
*(int rows) is the number of rows in our matrix. This is found to be 5 at runtime
*(int cols) is the number of cols in our matrix. This is also found to be 5 at runtime.
*(int **matrix[5][5]) is a matrix containing the 1's and 0's.
*/
int colnum;
int rownum;
int counts[cols];
for (colnum = 0; colnum < cols; colnum ++)
{
for (rownum = 0; rownum < rows; rownum ++)
{
counts[colnum] += matrix[rownum][colnum];
}
}
/*
*We store the result in output.
*/
output = counts;
}
int main(int argc, char **argv)
{
/*
*First, we create our matrix.
*/
int matrix[5][5] = {{0, 1, 1, 0, 1},
{1, 0, 1, 1, 0},
{1, 0, 0, 0, 1},
{0, 0, 1, 1, 1},
{1, 0, 1, 1, 0}};
int *Cs;
countCols(Cs, 5, 5, matrix);
/*Here, we tally up our 1's column by column.*/
int i;
printf("The column counts are:\n");
for (i = 0; i < 5; i ++)
{
printf("%d\n", Cs[i]);
/*Next, we print the counts on separate lines.*/
}
/*Finally, we return 0*/
return 0;
}
所以,我期待:
The column counts are:
3
1
4
3
3
然而,令我惊讶的是,我得到了:
The column counts are:
1768709983
1935631202
1953653108
1767992671
1600061550
这里发生了什么?还值得注意的是,当我编译时,我收到了这些警告:
C.c In function 'countCols':
C.c:12.22: warning: assignment makes integer from pointer without a cast
counts[colnum] += matrix[rownum][colnum];
C.c In function 'main':
C.c:27.23: warning: passing argument 4 of 'countCols' from incompatible pointer type
countCols(Cs, 5, 5, matrix);
C.c:3:7: note: expected 'int ** (*)[5]' but argument is of type 'int (*)[5]'
void *countCols(int *output, int rows, int cols, int **matrix[5][5])
任何建议将不胜感激。
编辑: 为了清楚起见,我将指向矩阵的指针而不是矩阵本身传递给 countCols。
【问题讨论】:
-
注意警告。数组不是指针,指针不是数组,多维数组也不是指针指向的指针。 Link to relevant C-FAQ section(顺便说一句,是什么让您相信
int **[5][5]可以可能与int **相同?)
标签: c function pointers gcc multidimensional-array