C-将元素数组转换为二维矩阵
问题描述:
这可能是一个愚蠢的问题,但我想知道是否存在一种有效的方法。
It might be a stupid question, but I wonder if there is a efficient way to do this.
情况:
int* array = malloc(n * m * sizeof(int));
//want to convert array into M[n][m]
我是什么现在做:
int** M = malloc(n * sizeof(int*));
for(int i = 0; i < n; i++, array += m)
M[i] = array;
我认为转换不应该如此复杂。是否提供任何简单的语法C?我可以声明 extern M [n] [m]
然后将其地址设置为数组吗?
I don't think the conversion should be this complex. Is there any simple syntax C provided? Can I declare an extern M[n][m]
then set its address to the array?
(错误为简单起见,示例中省略了处理和内存管理。只是将其视为某些功能的一部分。)
(error handling and memory management in the sample is omitted for simplicity. Just think it as a part of some function.)
答
之后:
int* array = malloc(n * m * sizeof(int));
您可以执行以下操作:
int (*M)[m] = (int(*)[m])array;
然后使用 M [1] [2]
例如。
您也可以首先这样做:
int (*M)[m] = malloc( n * sizeof *M );