我怀疑你想要的确实是两维阵,而是一阵一阵阵。
#include <stdio.h>
#include <stdlib.h>
int main()
{
const int NUM_ROWS = 100;
const int NUM_INTS_PER_ROW = 200;
// allocate a dynamic buffer of pointers; each pointer will
// point to a 1D array of integers
int ** rows = (int **) malloc(NUM_ROWS * sizeof(int *));
// for each row, allocate the array of integers
int i;
for (i=0; i<NUM_ROWS; i++) rows[i] = (int *) malloc(NUM_INTS_PER_ROW * sizeof(int));
// Populate the array
for (i=0; i<NUM_ROWS; i++)
{
int j;
for (j=0; j<NUM_INTS_PER_ROW; j++) rows[i][j] = 666;
}
// do stuff here...
// Finally, free the data
for (i=0; i<NUM_ROWS; i++) free(rows[i]);
free(rows);
return 0;
}
If you want a real 2D array (e.g. something that is laid out in a single contiguous block of memory, similar to int array[100][200]
, you re slightly out of luck, since C doesn t support dynamically-sized 2D arrays, but you can always fake it using a 1D array and a helper-function, like this:
#include <stdio.h>
#include <stdlib.h>
// Returns a pointer to the item in the array at the given row and column
int * GetPointerToArrayItem(int * array, int numIntsPerRow, int row, int col)
{
return array+(row*numIntsPerRow)+col;
}
int main()
{
const int NUM_ROWS = 100;
const int NUM_INTS_PER_ROW = 200;
int * array = (int *) malloc(NUM_ROWS * NUM_INTS_PER_ROW * sizeof(int));
// Populate the array
int i;
for (i=0; i<NUM_ROWS; i++)
{
int j;
for (j=0; j<NUM_INTS_PER_ROW; j++)
{
*GetPointerToArrayItem(array, NUM_INTS_PER_ROW, i, j) = 666;
}
}
// do stuff here...
// Finally, free the data
free(array);
return 0;
}