Preface:
If the size is known at compile time; you don't need to allocate anything; let the compiler take care of it (no malloc(), no free())
- int a[5][5];
- ...
- ...
- a[i][j] = xxx;
- ...
- ...
Now, if you want a 2D array of int, and the dimensions are not known at compile time, here's a way to do it. Suppose we want an array[size_x][size_y] of int, wheresize_x and size_y are variables. The "array" name will be a "pointer to a pointer to an int".
Example:
Here's an example (I have given size_x and size_y specific values for purposes of illustration, but these could be obtained from user input or from other program calculations, or whatever.)
- /* illustration of dynamically allocated 2D array */
- #include
- #include
- int main()
- {
- int i; /* general purpose variable used for loop index */
- int j; /* general purpose variable used for loop index */
- int **a; /* this is the array name */
- int size_x; /* this variable will be used for the first dimension */
- int size_y; /* this variable will be used for the second dimension */
- /* suppose we want an array of int: a[5][3] */
- size_x = 5;
- size_y = 3;
- /* allocate storage for an array of pointers */
- a = malloc(size_x * sizeof(int *));
- /* for each pointer, allocate storage for an array of ints */
- for (i = 0; i < size_x; i++) {
- a[i] = malloc(size_y * sizeof(int));
- }
- /* just for kicks, show the addresses (note: not all sequential) */
- /* assign an arbitrary value to each element */
- for (i = 0; i < size_x; i++) {
- for (j = 0; j < size_y; j++) {
- printf("&a[%d][%d] = %p\n", i, j, &a[i][j]); /* show the addresses */
- a[i][j] = i * size_y + j; /* just some unique number for each element */
- }
- printf ("\n");
- }
- /* now show the contents that were assigned */
- for (i = 0; i < size_x; i++) {
- for (j = 0; j < size_y; j++) {
- printf("a[%d][%d] = %2d\n", i, j, a[i][j]);
- }
- printf ("\n");
- }
- /* now for each pointer, free its array of ints */
- for (i = 0; i < size_y; i++) {
- free(a[i]);
- }
- /* now free the array of pointers */
- free(a);
- return 0;
- }
C++ Programmers: Do the same, but use new and delete instead of malloc() and free().
沒有留言:
張貼留言