怎么动态定义多维数组?我遇到的是要动态定义一个二维的。
在C语言中,动态定义一个二维数组可以通过使用malloc函数来实现。例如,假设你想要定义一个10行5列的二维数组,你可以使用以下代码来分配内存:
// Define the number of rows and columns
const int rows = 10;
const int columns = 5;
// Use malloc to allocate memory for the array
int **array = (int **)malloc(rows * sizeof(int *));
for (int i = 0; i < rows; i++)
{
array[i] = (int *)malloc(columns * sizeof(int));
}
这段代码会分配足够的内存来存储10行5列的二维数组。然后,你可以像访问普通数组一样使用下标来访问二维数组的元素。例如,要访问第2行第3列的元素,你可以使用以下代码:
int value = array[1][2];
当你完成使用二维数组时,你需要使用free函数来释放它所分配的内存。例如,要释放上面定义的二维数组,你可以使用以下代码:
// Free the memory allocated for the array
for (int i = 0; i < rows; i++)
{
free(array[i]);
}
free(array);
通过使用malloc和free函数,你可以在C语言中动态定义和使用二维数组。
int m=5,n=10;
int **p = (int**)malloc(sizeof(int*)*m);
for(int i=0;i<m;i++)
{
p[i] = (int*)malloc(sizeof(int)*n);
}