如何在运行时创建用C的二维阵列 [英] How to create at runtime a two dimensional array in C
本文介绍了如何在运行时创建用C的二维阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不能创建2个变量的二维数组(如 INT改编[I] [J]
不允许的),所以我将如何创建一个动态调整二维数组<? / p>
阵列的尺寸是在运行时在我的节目只公知的。该阵列是重新present一个网格。我将如何code在C?
解决方案
您必须分配一维数组:
为int *阵列=释放calloc(M * N,sizof(INT));
和访问它是这样的:
数组[I * N + J]。
编译器究竟该访问二维数组时,并可能会输出同样的code当 N
可以在编译时猜测。
I cannot create a 2D array from 2 variables (eg int arr[i][j]
not allowed) so how would I create a dynamically sized 2D array?
The dimensions of the array are only known at runtime in my program. The array is to represent a grid. How would I code this in C?
解决方案
You have to allocate a 1-dimensional array:
int* array = calloc(m*n, sizof(int));
And access it like this:
array[i*n + j]
The compiler does exactly this when accessing two-dimensional arrays, and will probably output the same code when n
can be guessed at compile time.
这篇关于如何在运行时创建用C的二维阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文