如何动态生成不定长度的数组
class Gobang {public: Gobang(unsigned short int r, unsigned short c):row(r),column(c){ _init_board(); }private: void _init_board() { for(int i=0; i<row; i++) { for(int s=0; s<column; s++) { } } } const unsigned short int row; const unsigned short int column; unsigned short int **board;};Gobang g(8,8);
//在堆中开辟一个4×5的二维int数组#include <stdio.h>#include <malloc.h>int **p;int i,j;void main() { p=(int **)malloc(4*sizeof(int *)); if (NULL==p) return; for (i=0;i<4;i++) { p[i]=(int *)malloc(5*sizeof(int)); if (NULL==p[i]) return; } for (i=0;i<4;i++) { for (j=0;j<5;j++) { p[i][j]=i*5+j; } } for (i=0;i<4;i++) { for (j=0;j<5;j++) { printf(" %2d",p[i][j]); } printf("\n"); } for (i=0;i<4;i++) { free(p[i]); } free(p);}// 0 1 2 3 4// 5 6 7 8 9// 10 11 12 13 14// 15 16 17 18 19
[解决办法]
//在堆中开辟一个4×5的二维int数组#include <stdio.h>#include <malloc.h>int **p;int i,j;void main() { p=(int **)malloc(4*sizeof(int *)); if (NULL==p) return; for (i=0;i<4;i++) { p[i]=(int *)malloc(5*sizeof(int)); if (NULL==p[i]) return; } for (i=0;i<4;i++) { for (j=0;j<5;j++) { p[i][j]=i*5+j; } } for (i=0;i<4;i++) { for (j=0;j<5;j++) { printf(" %2d",p[i][j]); } printf("\n"); } for (i=0;i<4;i++) { free(p[i]); } free(p);}// 0 1 2 3 4// 5 6 7 8 9// 10 11 12 13 14// 15 16 17 18 19