What are the different ways to define a two-dimensional array in the C language?
In the C language, there are several ways to define a two-dimensional array.
- Using static arrays: create a two-dimensional array by specifying fixed rows and columns when defining the array. For example:
int arr[3][3];
- Dynamic memory allocation can be used to create a two-dimensional array at runtime using the malloc() function. For example:
int **arr;
arr = (int **)malloc(3 * sizeof(int *));
for(int i=0; i<3; i++){
arr[i] = (int *)malloc(3 * sizeof(int));
}
- Using a pointer array: you can define an array of pointers, where each pointer points to a one-dimensional array, thus creating a two-dimensional array. For example:
int *arr[3];
for(int i=0; i<3; i++){
arr[i] = (int *)malloc(3 * sizeof(int));
}